繁体   English   中英

如何在JS中获取对象数组的特定属性?

[英]How to get specific properties of array of objects in JS?

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

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中做到这一点?

所以基本上最终的结果应该是:

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

您可以将reduce()map()结合使用。 基本上将主阵列缩小为所有cf项目的扁平数组。 这将检查c属性,以防对象没有它:

 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) 

这是一个快速的迭代解决方案,它不会溢出堆栈,不会假设目标结果值是数组(只有它们才会传播)并且不会硬编码子键名(它将探索任何数组值) 。

如果目标的子项与您要在搜索中包含的键匹配,则也可以使用( else if使用ifif交换else if )。

 const get = (data, target) => { const result = []; const stack = [data]; while (stack.length) { const curr = stack.pop(); for (const o of curr) { for (const k in o) { if (k === target) { if (Array.isArray(o[k])) { result.push(...o[k]); } else { result.push(o[k]); } } else if (Array.isArray(o[k])) { stack.push(o[k]); } } } } return result; }; 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(get(obj, "f")); 

您可以递归遍历任何对象和数组以获取给定属性。 这适用于任何深度,并不关心对象的结构:

 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}]}]}]; //curried function to grab a property by name off some object or array function grab(prop) { //naming the inner function means it can be called recursively by name return function recursiveGrab(target) { if (Array.isArray(target)) { const arrayResult = target .filter(x => typeof x === "object") //remove non-objects (and non-arrays) .filter(Boolean) //remove null .map(recursiveGrab); //recursively call for the remaining objects return flatten(arrayResult); //return a single dimensional array } //an object has the property - return it if (prop in target) { return target[prop]; } //object doesn't have the property - check all values return recursiveGrab(Object.values(target)); } } //small helper function. It's separated only to keep the logic for the traversal clear function flatten(arr) { return arr.reduce((acc, curr) => acc.concat(curr), []) } const grabF = grab('f'); console.log(grabF(obj)); 

我没注意到f总是在c里面。 我有这个递归和脏看的解决方案,适用于任何字段内的f

  const objArray = [ { a: 1, c: [ { d: 1, e: 'string', f: [ { value: 0, }, { value: 1, } ], }, ], d: [ { d: 1, e: 'string', f: [ { value: 'd', }, { value: 'd1', } ], }, ], }, { a: 2, c: [ { d: 2, e: 'string', f: [ { value: 3, }, { value: 4, } ], }, ], e: [ { d: 1, e: 'string', f: [ { value: 'e', }, { value: 'e1', } ], }, ], } ] const getFObject = (obj) => { let fObj = []; Object.keys(obj).some(key => { if (key === 'f') { fObj = obj[key]; return true; } if (Array.isArray(obj[key])) { obj[key].forEach(nestedObj => { fObj = fObj.concat(getFObject(nestedObj)) }); } return false; }); return fObj; } const newArray = objArray.reduce((acc, obj) => { return acc.concat(getFObject(obj)) }, []); console.log(newArray) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM