user984003
user984003

Reputation: 29557

Get key value of dictionary

How do I get the value from a javascript dictionary? (I don't even know if it's called a dictionary in javascript)

I get the following object (friends) from the facebook sdk. How do I, for example, loop through the names?

{data: [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}]}

Upvotes: 4

Views: 56556

Answers (4)

Vlad Bezden
Vlad Bezden

Reputation: 89587

You can use map function.

const obj = {
  data: [{
    id: "xxxxx",
    name: "Friend name"
  }, {
    id: "xxxxx",
    name: "Friend name"
  }]
}

obj.data.map(x => console.log(x.name))

Upvotes: 1

Andy
Andy

Reputation: 63524

Loop through the data array within the object that wraps the whole thing. Then target the name with object dot notation:

for (var i = 0, l = obj.data.length; i < l; i++) {
  console.log(obj.data[i].name);
}

Upvotes: 5

Naftali
Naftali

Reputation: 146310

You can loop through the data array like this:

var obj = {data: [{id: "xxxxx", name: "Friend name"}, {id: "xxxxx", name: "Friend name"}]};

//loop thru objects in data
obj.data.forEach(function(itm)  {
   console.log(itm.name);
});

Upvotes: 1

VisioN
VisioN

Reputation: 145408

In JavaScript dictionaries are objects. To access object properties you may use either dot notation or square brackets notation. To iterate an array you may use simple for loop.

var obj = {
        data: [{
            id: "xxxxx",
            name: "Friend name"
        }, {
            id: "xxxxx",
            name: "Friend name"
        }]
    };

for (var i = 0, len = obj.data.length; i < len; i++) {
    console.log(obj.data[i].name);
}

Upvotes: 11

Related Questions