javascript - 更新数组值的选择

标签 javascript

我有两个数组。每个数组可以有不同数量的对象,但它们每个都有相同的属性,但可以有不同的值。例如

var Array1 = [ { id: '1', value: a },
               { id: '2', value: b } ]

var Array2 = [ { id: '',  value: c },
               { id: '',  value: d },
               { id: '',  value: a } ]

我想要什么

AfterArray = [ { id: '1', value: a },
               { id: '3', value: c },
               { id: '4', value: d } ]

发生的情况是,如果 array1 的对象没有 array2 的值​​,则该对象将被删除。如果它确实有 array2 的值​​,它将保留原始 id。如果 array2 中的对象不在 array1 中,则会生成一个 id (UUID)。

我假设事情可能是这样的

afterArray = []

this.Array1.forEach((res, i) => {
    this.Array2.forEach((res2, 2) => {
       if(res.value == res2.value){
           afterArray = afterArray.concat(this.Array1[i])
        }
        else {
        // do something if values are not present then add to array.
        // if added, add id to those empty properties. 
        }
    })
})

谢谢!

最佳答案

您只需要对 Array2 进行简单的 mapping,并在其中添加 find,即可在 Array1 中查找匹配的值(如果存在):

const array1 = [
  {
    id: '1',
    value: 'a'
  },
  {
    id: '2',
    value: 'b'
  }
];
const array2 = [
  {
    id: '',
    value: 'c'
  },
  {
    id: '',
    value: 'd'
  },
  {
    id: '',
    value: 'a'
  }
];



const generateId = (() => {
  // example generator function, use your own instead
  let possibleIds = ['3', '4'];
  let i = -1;
  return () => {
    i++;
    return possibleIds[i];
  };
})();

const result = array2.map(({ id, value }) => {
  // find a matching value in array1 to merge the id:
  const foundArr1Item = array1.find(({ value: ar1Val }) => ar1Val === value);
  // otherwise, generate a new ID:
  if (foundArr1Item) return { value, id: foundArr1Item.id };
  return { value, id: generateId() };
});
console.log(result);

关于javascript - 更新数组值的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49959273/

相关文章:

php - 使用 php 向谷歌地图添加静态 1km 网格

javascript - Openlayers/Openstreetmap 背景是垂直条纹和压扁的

javascript - 使用模块模式时如何使用 JSDoc 记录子命名空间

javascript - 使用浏览器历史记录时,Rails link_to Remote True 问题

php - ui slider 上的值

javascript - JS promise : Allowing Propagation of Errors

javascript - 模板中的 Angular ng-href

javascript - 在 react 中处理用户输入。如何将 [e.target.name] 连接到另一个字符串

javascript - React 路由器 activeClassName 没有为子路由设置事件类

javascript - 在 ag-grid 中显示来自服务器的数据