如何从JSON返回嵌套在对象中的嵌套JavaScript数组的属性值?

时间:2016-11-28 02:01:42

标签: javascript arrays json functional-programming javascript-objects

给定一个包含许多对象的JS数组,这些对象都包含数组:

$diff = array_udiff($a, $b, 'arrayCmp');

如何有效地将最内层的数组(页面)值提取到数组中?

var data = [ 
   {id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]}, 
   {id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]}, 
   {id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];

5 个答案:

答案 0 :(得分:2)

最简单的方法是使用Array#map,如下所示:

var dataArray = data.map(function(o){return o.pages});

如果pages是一个对象数组(不是单个对象),这将产生一个数组数组,您需要将其展平,例如使用Array#reduce

dataArray = dataArray.reduce(function(a,b){return a.concat(b)}, []); 

答案 1 :(得分:2)

您正在寻找flatMap



var data = [ 
   {id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]}, 
   {id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]}, 
   {id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];

const concat = (xs, ys) => xs.concat(ys);

const prop = x => y => y[x];

const flatMap = (f, xs) => xs.map(f).reduce(concat, []);

console.log(
  flatMap(prop('pages'), data)
);




答案 2 :(得分:1)

以下是如何实现目标的实例:

var data = [ 
   {id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}, {url:"www.google.com", title: "Google"}]}, 
   {id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]}, 
   {id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];

var arr = Array();
var arr2 = Array();

// You can either iterate it like this:
for (var i = 0; i < data.length; i++) {
  // If you only want the first page in your result, do:
  // arr.push(data[i].pages[0]);

  // If you want all pages in your result, you can iterate the pages too:
  for (var a = 0; a < data[i].pages.length; a++) {
    arr.push(data[i].pages[a]);
  }
}

// Or use the array map method as suggested dtkaias 
// (careful: will only work on arrays, not objects!)
//arr2 = data.map(function (o) { return o.pages[0]; });

// Or, for all pages in the array:
arr2 = [].concat(...data.map(function (o) { return o.pages; }));

console.log(arr);
console.log(arr2);
// Returns 2x [Object { url="www.abc.com",  title="abc"}, Object { url="www.123.com",  title="123"}, Object { url="www.xyz.com",  title="xyz"}]

答案 3 :(得分:1)

如果通过“有效”实际上意味着“简明扼要”,那么

[].concat(...data.map(elt => elt.pages))

data.map将生成一个pages数组数组。 [].concat(...然后将所有pages数组作为参数传递给concat,它将所有元素组合成一个数组。

如果您使用ES5编程,则等效于

Array.prototype.concat.apply([], data.map(function(elt) { return elt.pages; }))

答案 4 :(得分:0)

使用数组map()&amp; reduce()方法:

var data = [ 
   {id: 1, name: "Fred", pages:[{url:"www.abc.com", title: "abc"}]}, 
   {id: 2, name: "Wilma", pages:[{url:"www.123.com", title: "123"}]}, 
   {id: 3, name: "Pebbles", pages:[{url:"www.xyz.com", title: "xyz"}]}
];
    
var dataArray = data.map(function(item) {
  return item.pages;
});    

dataArray = dataArray.reduce(function(a,b) {
  return a.concat(b);
}, []);

console.log(dataArray);