user10021926
user10021926

Reputation:

How to get the first key pair in array of JSON?

Currently, I have my JSON and a function that loops through the results and then through the URLs. I am trying to only get the first type value which is detail. I have tried looking for ways to get the first value and found that using [0] can work in some situations but not this one. Am I indexing incorrectly? and is there a more succinct way of coding this nested for loop?

const data = {
  "data": {
    "results": [{
      "name": "Deadpool",
      "urls": [{
          "type": "detail",
          "url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        },
        {
          "type": "wiki",
          "url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        },
        {
          "type": "comiclink",
          "url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        }
      ]
    }]
  }
};

function test(data) {
  const dataArr = data.data['results'];
  for (let i = 0; i < dataArr.length; i++) {
    console.log(dataArr[i].urls);
    const urlArr = dataArr[i].urls
    for (let j = 0; j < urlArr.length; j++) {
      console.log(urlArr[j].type[0]);
    }
  }
}

test(data);

Upvotes: 3

Views: 580

Answers (6)

bflemi3
bflemi3

Reputation: 6790

A functional approach...

Your question seems a little vague, but I think you're looking for the value of type from the first item in each urls array.

const data = {
    "data": {
        "results": [{
            "name": "Deadpool",
            "urls": [{
                "type": "detail",
                "url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
            },
            {
                "type": "wiki",
                "url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
            },
            {
                "type": "comiclink",
                 "url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
            }]
        }]
    }
};

const types = data.data.results.map(({ urls: [first, ...rest] }) => first.type);
console.log(types);


Let's break this down...

data.data.results.map(...)

Array.prototype.map will return a new array with the results of calling the provided function on every element in the results array.

({ urls: ... })

This is called destructuring. It defines a new variable, urls, that is assigned the value of the urls property as we iterate through the results items.

({ urls: [first, ...rest] })

The value of the urls variable we defined will be an array. We only care about the first item in the array, so we'll spread the array, defining a new variable called first that's assigned the value of the first item, and a variable, rest, that will be an array of the rest of the items. Basically, take the head of the array. These operations are called spread and rest, respectively.

({  urls: [first, ...rest] }) => first.type

Finally, return the value of the type property from the first urls item.


If I'm completely wrong

And you want the "details" item within each urls array, then a slight change will suffice:

const data = {
    "data": {
        "results": [{
            "name": "Deadpool",
            "urls": [{
                "type": "detail",
                "url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
            },
            {
                "type": "wiki",
                "url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
            },
            {
                "type": "comiclink",
                 "url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
            }]
        }]
    }
};

const urls = data.data.results.map(({ urls }) => 
    urls.find(({ type }) => type === 'detail')
);
console.log(urls);


If you'd like to learn more about functional programming, Eric Elliott wrote an excellent set of articles on functional programming in JavaScript. Here's the first one.

Upvotes: 3

Abhinav
Abhinav

Reputation: 51

Try this-

function test(data) 
{
    var dataArr = data.data.results;

    for (let i = 0; i < dataArr.length; i++) {

        const urlArr = dataArr[i].urls
        for (let j = 0; j < urlArr.length; j++) {
            console.log(urlArr[0].type);
        }
    }

}

Upvotes: 2

Ashish
Ashish

Reputation: 4330

If the format of your data is fixed you can use. You can also try different approaches of safe reading data from object. You can use utilities like these:

data.data['results'][0].urls[0]

If you are not sure about the 0th index you can use find:

data.data['results'][0].urls.find(url => url.type === 'detail')

Upvotes: 2

quirimmo
quirimmo

Reputation: 9988

const data = {
  "data": {
    "results": [{
      "name": "Deadpool",
      "urls": [{
          "type": "detail",
          "url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        },
        {
          "type": "wiki",
          "url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        },
        {
          "type": "comiclink",
          "url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        }
      ]
    }]
  }
};

console.log(data.data.results.map(el => el.urls).flat().find(el => el.type === 'detail'));

Upvotes: 0

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

Something like this?

const data = {
  "data": {
    "results": [{
      "name": "Deadpool",
      "urls": [{
          "type": "detail",
          "url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        },
        {
          "type": "wiki",
          "url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        },
        {
          "type": "comiclink",
          "url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        }
      ]
    }]
  }
};

const result = [].concat.apply([], data.data.results.map(x => x.urls.map(y => y.type)))[0];
console.log(result);

Upvotes: 0

Mosh Feu
Mosh Feu

Reputation: 29287

You can use find to find the exact element by type prop.

const data = {
  "data": {
    "results": [{
      "name": "Deadpool",
      "urls": [{
          "type": "detail",
          "url": "http://marvel.com/characters/12/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        },
        {
          "type": "wiki",
          "url": "http://marvel.com/universe/Deadpool_(Wade_Wilson)?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        },
        {
          "type": "comiclink",
          "url": "http://marvel.com/comics/characters/1009268/deadpool?utm_campaign=apiRef&utm_source=6fa9bcf637a9185ee2e3035cb2d3b465"
        }
      ]
    }]
  }
};

function test(data) {
  const dataArr = data.data['results'];
  for (let i = 0; i < dataArr.length; i++) {
    //console.log(dataArr[i].urls);
    const urlArr = dataArr[i].urls
    const detail = urlArr.find(url => url.type == 'detail');
    console.log(detail.url);
  }
}

test(data);

Upvotes: 1

Related Questions