![](/img/trans.png)
[英]Using JavaScript to compare 2 arrays and create a new array of objects which does not contains the objects that match by id field
[英]Compare 2 objects to create a new array of objects in javascript
我有两个要素:水果和板条箱
fruits
是一个包含不同水果列表的数组,例如:
["apple","orange","mango","pear"]
crates
是一系列包含水果的对象,例如:
[{id:1,fruit_name: "apple"},{id:2, fruit_name: "pear"}]
我想根据以下条件创建一个新的对象数组:-检查水果数组中的实体是否存在于任何包装箱数组中。
如果存在,则最终对象应该具有fruit_name
属性以及另一个称为tested
属性设置为true
。 如果不存在,那么tested
应该是false
;
考虑以上情况,最终输出应如下:
[
{fruit_name: "apple", tested: true},
{fruit_name: "orange", tested: false},
{fruit_name: "mango", tested: false},
{fruit_name: "pear", tested: true},
]
我尝试过如下:
fruits.forEach(x => {
crates.filter((y) => {
let temp;
if (x == y.fruit_name) {
temp = {
fruit: x,
tested: true
}
}
else {
temp = {
time: x,
tested: false
}
}
testedCrates.push(temp);
})
})
这样做的问题是,它会将每个水果两次返回,并同时包含两个用于测试属性的值。
我得到的输出如下:
[
{fruit: "apple", tested: true},
{time: "apple", tested: false},
{time: "orange", tested: false},
{time: "orange", tested: false},
{time: "mango", tested: false},
{time: "mango", tested: false},
{time: "pear", tested: false},
{time: "pear", tested: false}
]
请为此提供一些解决方案。 此外,如果有更好的方法使用es6方法,将很有帮助。 提前致谢。
您可以使用array#map
和array#some
检查crates
是否存在水果。
var fruits = ["apple","orange","mango","pear"], crates = [{id:1,fruit_name: "apple"},{id:2, fruit_name: "pear"}]; var result = fruits.map(fruit => { var tested = crates.some(({fruit_name}) => fruit_name === fruit); return {'fruit_name' : fruit, tested}; }); console.log(result);
创建一组存在于板条箱中的水果,然后将水果数组映射到所需的形式:
const fruits = ["apple","orange","mango","pear"] const crates = [{id:1,fruit_name: "apple"},{id:2, fruit_name: "pear"}]; const cratesSet = new Set(crates.map(({ fruit_name }) => fruit_name)); const result = fruits.map((fruit_name) => ({ fruit_name, tests: cratesSet.has(fruit_name) })); console.log(result);
您可以在检查集合的同时为crates
Set
,并为新数组迭代fruits
。
var fruits = ["apple", "orange", "mango", "pear"], crates = [{ id: 1, fruit_name: "apple" }, { id: 2, fruit_name: "pear" }], cSet = new Set(crates.map(({ fruit_name }) => fruit_name)), result = fruits.map(fruit_name => ({ fruit_name, tested: cSet.has(fruit_name) })); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
fruits.map(fruit => ({
fruit_name: fruit,
tested: crates.some(crate => crate.fruit === fruit),
}));
fruits.map(fruit=>({
fruit_name: fruit,
tested: crates.some(x=>x.fruit_name === fruit)
}))
fruits.forEach(x => {
let temp = { fruit: x, tested: false }
crates.filter(y => {
if (x === y.fruit_name)
temp = { fruit: x, tested: true }
})
testedCrates.push(temp);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.