3

如何从 javascript 字典中获取值?(我什至不知道它是否在javascript中称为字典)

我从 facebook sdk 获得以下对象(朋友)。例如,我如何遍历名称?

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

4 回答 4

10

在 JavaScript 中,字典是对象。要访问对象属性,您可以使用点表示法或方括号表示法。要迭代数组,您可以使用简单for循环。

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);
}
于 2013-10-10T14:48:23.473 回答
4

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);
}
于 2013-10-10T14:50:50.223 回答
0

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);
});
于 2013-10-10T14:49:23.573 回答
0

您可以使用地图功能。

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

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

于 2016-09-26T15:33:26.467 回答