如何在JS中获取对象数组的特定属性? [英] How to get specific properties of array of objects in JS?

查看:138
本文介绍了如何在JS中获取对象数组的特定属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码和测试数据:

I have the following code and test data:

const getNestedObject = (nestedObj, pathArr) => {
    return pathArr.reduce((obj, key) => {
        return (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj;
    });
}

const obj = 
 [
  {
      a: 1,
      c: [
        {
          d: 1,
          e: 'string',
          f: [
            {
              value: 0,
            },
            {
              value: 1,
            }
          ],
        },
      ],
  },
    {
      a: 2,
      c: [
        {
          d: 2,
          e: 'string',
          f: [
            {
              value: 3,
            },
            {
              value: 4,
            }
          ],
        },
      ],
  },
 ];

console.log(obj);
const fs = obj.map(o => getNestedObject(o, ['c', 'f']));
console.log(fs);

我要给定的对象数组如下所示,我想从数组中的每个对象中仅获取名为 f 的属性.因此,基本上最终结果应该是每个对象的 f 值数组.由于"f"是一个数组,因此,我非常希望最终结果是一个包含所有"f"属性中的元素的数组,因此每种"f"都应散布开来,因此我只有一个数组.我上面的 getNestedObject 函数似乎不起作用,就像下面的 console.log 语句返回整个对象一样.有什么想法在JS中做到这一点吗?

What I want to do is given the array of objects shown below, I want to get only the property called f from every object in the array. So, basically end result should be array of f values of every object. Since 'f' is an array, I would highly appreciate the end result to be just one array with elements from all 'f' properties, so kind of every of these 'f' to be spread out, so I have one array. My above getNestedObject function does not seem to work, as when the console.log statement below returns the whole object. Any ideas how to do this in JS?

因此,基本上,最终结果应该是:

So basically the end result should be:

[{ value: 0 }, { value: 1 }, { value: 3 }, {value: 4 }]

推荐答案

您可以将 reduce() map()结合使用.基本上将主数组简化为所有 c.f 项的扁平数组.这将检查 c 属性,以防万一对象没有该属性:

You can combine reduce() with map(). Basically reduce your main array into an flattened array of all the c.f items. This checks for the c property just in case the object doesn't have it:

const obj = [{a: 1,c: [{d: 1,e: 'string',f: [{value: 0,},{value: 1,}],},],},{a: 2,c: [{d: 2,e: 'string',f: [{value: 3,},{value: 4,}],},],},];

let Fs = obj.reduce((arr, item) => 
    item.c
    ? arr.concat(...item.c.map(itemc => itemc.f ))  // concat for flattened rather than nested arrays
    : arr
    , []);

console.log(Fs)

这篇关于如何在JS中获取对象数组的特定属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆