【问题标题】:Add new property to object if found in array如果在数组中找到,则将新属性添加到对象
【发布时间】:2021-01-15 18:49:45
【问题描述】:

我有一个对象数组,每个对象都有一个 id。我有另一个带有 id 值的数组。如果在 arrayOfIds 中找到对象 id,我想添加名为 found 的新属性并将其设置为 true。我正在考虑使用 findIndex 作为可能的函数在这里使用。

const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const arrayOfIds = ['456']

预期输出

const arrayOfObjects = [ { id: '123' }, { id: '456', found: true }, { id: '789' } ]

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 任何答案对你有用吗?

标签: javascript arrays object ecmascript-6


【解决方案1】:

const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
const arrayOfIds = ['456']

arrayOfObjects.map((object) => {
  if(arrayOfIds.includes(object.id)) {
    object.found = true;
  }
})

console.log(arrayOfObjects);

【讨论】:

  • map 函数不会改变原始数组。您应该打印返回的数组。
  • 不用了,数组中的对象已经变异了。
  • 前面说过,不需要返回新数组,数组只是对象引用的数组。对象已更新,这很重要。运行代码并查看输出。
【解决方案2】:

我认为将您的 arrayOfIds 转换为 Set 以允许 O(1) 查找是有意义的。

const ids = new Set(arrayOfIds);
const augmentedObjects = arrayOfObjects.map(obj => {
  if (ids.has(obj.id)) {
    obj.found = true;
  }
  return obj;
});

【讨论】:

    【解决方案3】:

    您可以从数组中创建一个Set 并将Array#mapSet#has 一起使用。

    const arrayOfObjects = [ { id: '123' }, { id: '456' }, { id: '789' } ]
    const ids = new Set(['456']);
    const res = arrayOfObjects.map(o => ({...o, ...ids.has(o.id) && {found: true}}));
    console.log(res);

    【讨论】:

      【解决方案4】:

      您可以映射对象并使用found 属性传播对象。

      const output = arrayOfObjects.map((obj) => {
         if (arrayOfIds.includes(obj.id)) {
            return {  ...obj, found: true };
         }
         return obj;
      });
      

      【讨论】:

        【解决方案5】:

        您可以通过创建一个查找对象来做到这一点。从arrayOfIds 创建查找对象,并在遍历arrayOfObjects 数组时使用该查找对象并进行某些更改。

        const arrayOfObjects = [{ id: '123' }, { id: '456' }, { id: '789' }];
        const arrayOfIds = ['456'];
        const lookup = Object.fromEntries(arrayOfIds.map((x) => [x, { found: true }]));
        const ret = arrayOfObjects.map((x) => ({ ...x, ...lookup[x.id] }));
        console.log(ret);

        【讨论】:

          【解决方案6】:

          只需在对象数组上运行map,然后使用includes 通过扩展现有对象来添加show: true,否则返回原始对象。 你可以试试这样的

          const arrayOfObjects = [{ id: "123" }, { id: "456" }, { id: "789" }];
          const arrayOfIds = ["456"];
          const result = arrayOfObjects.map((item) => {
            if (arrayOfIds.includes(item.id)) {
                return {
                        ...item,
                        found: true
                };
            }
            return item;
          });
          console.log(result);

          【讨论】:

            猜你喜欢
            • 2022-09-22
            • 2021-03-22
            • 2017-09-18
            • 2017-08-08
            • 2016-09-14
            • 1970-01-01
            • 2019-08-21
            • 1970-01-01
            相关资源
            最近更新 更多