我有两个数组。每个数组可以有不同数量的对象,但它们每个都有相同的属性,但可以有不同的值。例如
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 进行简单的 map
ping,并在其中添加 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/