通过迭代JSON对象并只获取其内部数组的1来创建新数组

Create new array from iterating JSON objects and getting only 1 of its inner array

本文关键字:数组 创建 新数组 内部 JSON 迭代 对象 获取      更新时间:2023-09-26

请在此处查看jsfiddle:https://jsfiddle.net/remenyLx/2/

我有包含对象的数据,每个对象都有一组图像。我只想要每个对象的第一个图像。

var data1 = [
    {
    id: 1,
    images: [
      { name: '1a' },
      { name: '1b' }
    ]
  },
  {
    id: 2,
    images: [
      { name: '2a' },
      { name: '2b' }
    ]
  },
  {
    id: 3
  },
  {
    id: 4,
    images: []
  }
];
var filtered = [];
var b = data1.forEach((element, index, array) => {
    if(element.images && element.images.length) 
      filtered.push(element.images[0].name);
});
console.log(filtered);

输出需要平坦:

['1a', '2a']

我怎样才能让它更漂亮?

我不太熟悉JS mapreducefilter,我认为这些会使我的代码更明智;CCD_ 4感觉没有必要。

首先可以过滤掉没有正确images属性的元素,然后将其映射到新数组:

const filtered = data1
  .filter(e => e.images && e.images.length)
  .map(e => e.images[0].name)

要在一个循环中做到这一点,您可以使用reduce函数:

const filtered = data1.reduce((r, e) => {
  if (e.images && e.images.length) {
    r.push(e.images[0].name)
  }
  return r
}, [])

您可以使用reduce()返回此结果。

var data1 = [{
  id: 1,
  images: [{
    name: '1a'
  }, {
    name: '1b'
  }]
}, {
  id: 2,
  images: [{
    name: '2a'
  }, {
    name: '2b'
  }]
}, {
  id: 3
}, {
  id: 4,
  images: []
}];
var result = data1.reduce(function(r, e) {
  if (e.hasOwnProperty('images') && e.images.length) r.push(e.images[0].name);
  return r;
}, [])
console.log(result);

所有答案都在投影最终结果之前创建新数组:(filtermap各创建一个新数组(,所以基本上是创建两次

另一种方法是仅产生预期值

使用迭代器函数

function* foo(g)
{
    for (let i = 0; i < g.length; i++)
    {
        if (g[i]['images'] && g[i]["images"].length)
            yield g[i]['images'][0]["name"];
    }
}
var iterator = foo(data1) ;
var result = iterator.next();
 while (!result.done)
{
    console.log(result.value)
    result = iterator.next();
}

这将不会创建任何额外的数组,并且只返回期望的值!

但是,如果您必须返回一个数组,而不是对实际值执行某些操作,那么请使用此处建议的其他解决方案。

https://jsfiddle.net/remenyLx/7/