【问题标题】:Create new array from iterating JSON objects and getting only 1 of its inner array从迭代 JSON 对象创建新数组并仅获取其内部数组的 1 个
【发布时间】:2016-09-08 09:59:02
【问题描述】:

在此处查看 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 不太熟悉,我认为这些会让我的代码更合理; forEach 感觉没必要。

【问题讨论】:

  • filter , reducemap
  • 你的认识很好
  • 你不需要b变量,它永远是undefined

标签: javascript arrays json ecmascript-6


【解决方案1】:

首先你可以filter out 没有正确的images 属性的元素,然后map 到新数组:

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
}, [])

【讨论】:

    【解决方案2】:

    您可以使用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);

    【讨论】:

      【解决方案3】:

      所有答案都是在投影最终结果之前创建新数组:(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/

      【讨论】:

      • OP 不想要一个数组吗?此外,当迭代器完成时,这会打印 undefined
      • @CodingIntrigue 是的,已修复 tnx。顺便说一句,我不认为 OP 知道它不必在数组中,当然可以随时调用 push。
      猜你喜欢
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 2018-12-11
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      相关资源
      最近更新 更多