【发布时间】:2018-06-05 16:43:52
【问题描述】:
我有两个元素的水果和板条箱
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 方法有更好的方法会有所帮助。 提前致谢。
【问题讨论】:
标签: javascript arrays typescript ecmascript-6