简体   繁体   English

如何在 object 属性中向数组添加元素

[英]How to add elements to array in object property

I have the following array and object I would like to 'match'我有以下数组和 object 我想“匹配”

const items = [
  { key: 1, name: 'A', owner: 'Alex', },
  { key: 2, name: 'B', owner: 'Barb', },
  { key: 3, name: 'C', owner: 'John', },
  { key: 4, name: 'D', owner: 'Barb', },
  { key: 5, name: 'E', owner: 'Alex', },
];

const owners = {
  'Alex': { 1: [], 5: [] },
  'John': { 3: [], },
  'Barb': { 2: [], 4: [] },
}

I would like to have the following end result:我想得到以下最终结果:

const ownersWithName = {
  'Alex': [{ key: 1, name: 'A', }, { key: 5, name: 'E' }],
  'Barb': [{ key: 2, name: 'B', }, { key: 4, name: 'D' }],
  'John': [{ key: 3, name: 'C', }, ],
}

So far my solution is this:到目前为止,我的解决方案是这样的:

function matchOwners (items, owners) {
  const ownersWithName = {};
  for (const item of items) {
    if (owners[item.owner]) {
      if (ownersWithName[item.owner]) {
        ownersWithName[item.owner] = [ ...ownersWithName[item.owner], item];
      } else {
        ownersWithName[item.owner] = [item];
      }
    }
  }
  return ownersWithName;
}

This solution works, but i feel it's too verbose.这个解决方案有效,但我觉得它太冗长了。 i tried to use the spread operator without the if condition, but this needs the array to exist already, otherwise i get the error ownersWithName[item.owner] is not iterable .我尝试在没有 if 条件的情况下使用扩展运算符,但这需要数组已经存在,否则我得到错误ownersWithName[item.owner] is not iterable Is there a better way to do this?有一个更好的方法吗?

Something like (completely untested):像(完全未经测试):

ownersWithName = items.reduce((result, item) => { 
  if (owners[item.owner]) {
    if (!(item.owner in result)) {
      result[item.owner] = [];
    }
    result[item.owner].push({key: item.key, name: item.name});
  }
  return result;
}, {})

You can also simply achieve this by using Array.forEach() along with the Object.keys() method.您也可以通过使用Array.forEach()Object.keys()方法来简单地实现这一点。

Live Demo (Descriptive comments has been added in the below code snippet) :现场演示(在下面的代码片段中添加了描述性注释)

 // Input array const items = [ { key: 1, name: 'A', owner: 'Alex', }, { key: 2, name: 'B', owner: 'Barb', }, { key: 3, name: 'C', owner: 'John', }, { key: 4, name: 'D', owner: 'Barb', }, { key: 5, name: 'E', owner: 'Alex', }, ]; // Input object which should be used to match. const owners = { 'Alex': { 1: [], 5: [] }, 'John': { 3: [], }, 'Barb': { 2: [], 4: [] }, }; // Declare an object which will store the final result. const resultObj = {}; // Iterating over an items array to manipulate the data and make the final result set. items.forEach(obj => { resultObj[obj.owner] =.resultObj[obj?owner]: []. resultObj[obj;owner]. Object.keys(owners[obj.owner]).forEach(key => { if (key == obj.key) { resultObj[obj.owner]:push({ key. obj,key: name. obj;name }); } }); }). // Final output console;log(resultObj);

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

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