如何过滤 JavaScript 中的嵌套对象 属性?

How to filter on a nested object property in JavaScript?

以下 returns 所有 arrProps 具有匹配的 arrValues 值:

const arr = [
{ arrProps: [{name: '1', prop2: 'aaa'}], arrValues: ['apple', 'orange'] },
{ arrProps: [{name: '2', prop2: 'bbb'}], arrValues: ['taco', 'orange' ] },
{ arrProps: [{ name: '3', prop2: 'ccc' }], arrValues: ['fish', 'apple', 'orange'] }
];

const result = arr
  .flatMap(({ arrValues }) => arrValues )  // all values
  .filter((value, index, coll) => coll.indexOf(value) === index) //unique values
  .reduce((acc, value) => {
      const parentProp = arr      // name, prop2, arrValues
          .filter((obj) => obj.arrValues.includes(value))
          .map((obj) => obj.arrProps[0].name);
          //.map((obj) => [{ source: obj.arrProps[0].name, value: obj.arrValues[0], sourceID: null}]);

      acc[value] = (acc[value] ? [...acc[value], parentProp] : [parentProp])
      .join(',');
      acc[value] = parentProp
      
    return acc;
}, {})

console.log(result);
console.table(result);

我需要向 arrValues 添加额外的属性,从而使用对象而不是值:

const arr = [
    { arrProps: [{ name: '1', prop2: 'aaa' }], arrValues: [{ symbol: 'apple', id: '1.apple' }, {symbol: 'orange', id: '1.orange'}] },
    { arrProps: [{ name: '2', prop2: 'bbb' }], arrValues: [{ symbol: 'fish', id: '2.fish' }, { symbol: 'pizza', id: '2.pizza' }, { symbol: 'red', id: '2.red' }] },
    { arrProps: [{ name: '3', prop2: 'ccc' }], arrValues: [{ symbol: 'grape', id: '3.grape'}, { symbol: 'apple', id: '3.apple' }] },
];

从简单的 'apple' 开始,我需要添加一些额外的唯一标识值,即 { symbol: 'apple', id: '1.apple' }

我确定它在这里:

aMap.filter((value, index, coll) => coll.indexOf(value) === index) // <--- filter issue

返回对象(之前的数据模型,只是值'apple','orange'...):

Array(7) [Object, Object, Object, Object, Object, Object, Object]
    [[Prototype]]: Array(0)
    length: 7
    0: Object {symbol: "apple", id: "1.apple"}
    1: Object {symbol: "orange", id: "1.orange"}
    2: Object {symbol: "fish", id: "2.fish"}
    3: Object {symbol: "pizza", id: "2.pizza"}
    4: Object {symbol: "red", id: "2.red"}
    5: Object {symbol: "grape", id: "3.grape"}
    6: Object {symbol: "apple", id: "3.apple"}
    __proto__: Array(0)

我在尝试过滤 arrValues[0].symbol 时遇到了麻烦。然后我需要将 arrValues[0].id 附加到结果中。我想用 arrProps 创建一个新对象,唯一 ID 最好。

所以在apple的情况下,第一列应该呈现{parent: arrProps[0], id: arrValues[0].id},等等

---更新---

除了显示 arrPorps[0].name 的名称,我还需要返回一个对象,按照上面的最后一行(对原始问题的更改)。

我曾想过找到一些方法将 arrProps 附加到输出,但被困在那里。因为我可以混合数据模型,所以我向 arrValues[] 添加了一些额外的标识属性(等等,这和 arrProps[] 真的需要是一个数组吗,它只是一个对象 - 重构?):

const arr = [
    { arrProps: [{ name: '1', prop2: 'aaa' }], arrValues: [{ exchange: '1', symbol: 'apple', id: '1.apple' }, {exchange: '1', symbol: 'orange', id: '1.orange' }] },
    { arrProps: [{ name: '2', prop2: 'bbb' }], arrValues: [{ exchange: '2', symbol: 'fish', id: '2.fish' }, { exchange: '2', symbol: 'pizza', id: '2.pizza' }, { exchange: '2', symbol: 'red', id: '2.red' }] },
    { arrProps: [{ name: '3', prop2: 'ccc' }], arrValues: [{ exchange: '3', symbol: 'grape', id: '3.grape' }, { exchange: '3', symbol: 'apple', id: '3.apple' }] },
];

然后更改输出,创建一个输出对象,

发件人:.map(({ arrProps }) => arrProps[0].name)

收件人:.map(({ arrValues }) => [{ exchange: arrValues[0].exchange, symbol: arrValues[0].symbol, id: arrValues[0].id }]);

整个更新代码:

    const arr = [
        { arrProps: [{ name: '1', prop2: 'aaa' }], arrValues: [{ exchange: '1', symbol: 'apple', id: '1.apple' }, {exchange: '1', symbol: 'orange', id: '1.orange' }] },
        { arrProps: [{ name: '2', prop2: 'bbb' }], arrValues: [{ exchange: '2', symbol: 'fish', id: '2.fish' }, { exchange: '2', symbol: 'pizza', id: '2.pizza' }, { exchange: '2', symbol: 'red', id: '2.red' }] },
        { arrProps: [{ name: '3', prop2: 'ccc' }], arrValues: [{ exchange: '3', symbol: 'grape', id: '3.grape' }, { exchange: '3', symbol: 'apple', id: '3.apple' }] },
    ];
    
    const objectValues = arr.flatMap(({ arrValues }) => arrValues);  // not necessary if we refactor, removing these arrays?
    const values = objectValues.map(({ symbol }) => symbol);
    const uniqueValues = [...new Set(values)];
    const result = uniqueValues.reduce((acc, value) => {
        acc[value] = arr
            .filter(({ arrValues }) => {
                const symbols = arrValues.map(({ symbol }) => symbol)
                return symbols.includes(value);
            })
            //.map(({ arrProps }) => arrProps[0].name)
            .map(({ arrValues }) => [{ exchange: arrValues[0].exchange, symbol: arrValues[0].symbol, id: arrValues[0].id }]);
            //.join(',');
        return acc;
    }, {});
    
    console.log("RAW:" + JSON.stringify(result));
    
    console.log(result);
    console.table(result);
    
    Object.entries(result).forEach(([k, v]) => {
        console.log(`      ----] The value '${k}' exists in:`);
        console.table(JSON.stringify(v));
        //console.log("The pair: ", k)
        ////console.log("The value: ", v)
        v.forEach(_pool => console.log(`
            Exchange: ${_pool[0].exchange}
            symbol: ${_pool[0].symbol}
            ID: ${_pool[0].id}
        `));
    })

两个问题:

  1. 我认为数据模型中不需要数组
  2. 输出数据错误。
{
   "apple":[
      [
         {
            "exchange":"1",
            "symbol":"apple",
            "id":"1.apple"
         }
      ],
      [
         {
            "exchange":"3",
            "symbol":"grape",   // should be "apple"
            "id":"3.grape"      // should be "3.apple"
         }
      ]
   ],
   "orange":[
      [
         {
            "exchange":"1",
            "symbol":"apple",   // should be "orange"
            "id":"1.apple"      // should be "1.orange"
         }
      ]
   ],
   "fish":[
      [
         {
            "exchange":"2",
            "symbol":"fish",
            "id":"2.fish"
         }
      ]
   ],
   "pizza":[
      [
         {
            "exchange":"2",
            "symbol":"fish",   // should be pizza
            "id":"2.fish"      // should be 2.pizza
         }
      ]
   ],
   "red":[
      [
         {
            "exchange":"2",
            "symbol":"fish",   // should be "red"
            "id":"2.fish"      // should be "2.red"
         }
      ]
   ],
   "grape":[
      [
         {
            "exchange":"3",
            "symbol":"grape",
            "id":"3.grape"
         }
      ]
   ]
}

--- 更新 2 ---

回到我对数据错误的怀疑,嗯,看起来是这样。

而不是每个对象都根据其相关的常用词命名:apple, orange, fish,这需要参数化并删除多余的数组(伪代码对象):

[{
    itemName: 'apple',
    itemParam2: 'xxx',
    itemPools: [
        { source: '3', symbol: 'apple', id: '3.apple', cost: '0.00' },
        { source: '4', symbol: 'apple', id: '4.apple', cost: '0.00' },
        { source: '4', symbol: 'apple', id: '4b.apple', cost: '0.00' }
      ],
    itemName: 'orange',
    itemParam2: 'yyy',
    itemPools: [
    ...
    itemName: 'fish',
    itemParam2: 'zzz',
    itemPools: [
    ...
}]

仅供参考:需要验证结果数据对象的格式是否正确

实际上,orangefish 应该从模型中省略,因为 itemPools.length 不是 > 1。

因此除了更新的模型属性外,只应添加 itemPool.length > 1 的项目。

没有这个,我无法find an array item by its property

为了提供一些未来的背景,here

经过几次尝试,我改变了解决方案。在我看来,它现在更简单,更通用。

const arr = [
    { arrProps: [{ name: '1', prop2: 'aaa' }], arrValues: [{ symbol: 'apple', id: '1.apple' }, {symbol: 'orange', id: '1.orange'}] },
    { arrProps: [{ name: '2', prop2: 'bbb' }], arrValues: [{ symbol: 'fish', id: '2.fish' }, { symbol: 'pizza', id: '2.pizza' }, { symbol: 'red', id: '2.red' }] },
    { arrProps: [{ name: '3', prop2: 'ccc' }], arrValues: [{ symbol: 'grape', id: '3.grape'}, { symbol: 'apple', id: '3.apple' }] },
];

const result = arr.reduce((acc, { arrProps: [{ name }], arrValues }) => {
    arrValues.map(({ symbol }) => symbol)
    .forEach((value) => {
        acc[value] = acc[value] ? `${acc[value]},${name}`: name;
    });
    return acc;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

如果我们考虑 以前的方法 和过滤器,解决方案可能如下:

const arr = [
    { arrProps: [{ name: '1', prop2: 'aaa' }], arrValues: [{ symbol: 'apple', id: '1.apple' }, {symbol: 'orange', id: '1.orange'}] },
    { arrProps: [{ name: '2', prop2: 'bbb' }], arrValues: [{ symbol: 'fish', id: '2.fish' }, { symbol: 'pizza', id: '2.pizza' }, { symbol: 'red', id: '2.red' }] },
    { arrProps: [{ name: '3', prop2: 'ccc' }], arrValues: [{ symbol: 'grape', id: '3.grape'}, { symbol: 'apple', id: '3.apple' }] },
];

const objectValues = arr.flatMap(({ arrValues }) => arrValues);
const values = objectValues.map(({ symbol }) => symbol);
const uniqueValues = [...new Set(values)];
const result = uniqueValues.reduce((acc, value) => {
  acc[value] = arr
    .filter(({ arrValues }) => {
      const symbols = arrValues.map(({ symbol }) => symbol)
      return symbols.includes(value);
    })
    .map(({ arrProps }) => arrProps[0].name)
    .join(',');
  return acc;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

---更新---

const arr = [
        { arrProps: [{ name: '1', prop2: 'aaa' }], arrValues: [{ exchange: '1', symbol: 'apple', id: '1.apple' }, {exchange: '1', symbol: 'orange', id: '1.orange' }] },
        { arrProps: [{ name: '2', prop2: 'bbb' }], arrValues: [{ exchange: '2', symbol: 'fish', id: '2.fish' }, { exchange: '2', symbol: 'pizza', id: '2.pizza' }, { exchange: '2', symbol: 'red', id: '2.red' }] },
        { arrProps: [{ name: '3', prop2: 'ccc' }], arrValues: [{ exchange: '3', symbol: 'grape', id: '3.grape' }, { exchange: '3', symbol: 'apple', id: '3.apple' }] },
    ];
    
    
const result = arr.reduce((acc, { arrValues }) => {
    arrValues.forEach((value) => {
        acc[value.symbol] = acc[value.symbol] 
          ? [...acc[value.symbol], value] 
          : [value]; 
    });
    return acc;
}, {});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

---更新 3---

const arr = [
{ arrProps: [{ name: '1', prop2: 'aaa' }], arrValues: [{ exchange: '1', symbol: 'apple', id: '1.apple' }, {exchange: '1', symbol: 'orange', id: '1.orange' }] },
{ arrProps: [{ name: '2', prop2: 'bbb' }], arrValues: [{ exchange: '2', symbol: 'fish', id: '2.fish' }, { exchange: '2', symbol: 'pizza', id: '2.pizza' }, { exchange: '2', symbol: 'red', id: '2.red' }] },
{ arrProps: [{ name: '3', prop2: 'ccc' }], arrValues: [{ exchange: '3', symbol: 'grape', id: '3.grape' }, { exchange: '3', symbol: 'apple', id: '3.apple' }] },
];

const reduceArray = (data, poolsCountEdge = 1) => {
  const result = data.reduce((acc, { arrValues }) => {
      arrValues.forEach((value) => {
         const item = acc.find(({ name }) => name === value.symbol);
         if (item) {
           item.pools.push(value);
           item.poolsCount = item.pools.length;
         } else {
           acc.push({ name: value.symbol, poolsCount: 1, pools: [value] }); 
         }
      });
      
      return acc;
  }, []);
  
  return result.filter(({ poolsCount }) => poolsCount > poolsCountEdge)
};

console.log(reduceArray(arr));
.as-console-wrapper { max-height: 100% !important; top: 0; }