我有两个数组;
let items = {
search: [
['car', 'door', 'pen']
]
}
let data.props = [];
data.props = [
{label: "car"},
{label: "window"},
{label: "kettle"},
{label: "chair"},
{label: "door"},
]
如何使用es6检查/比较两个数组?因为items[]
是一个嵌套数组,所以对我来说有些棘手。
我只检查第一个项目。
if (data.props['0'].label === items.search['0'].values['0']) {
let searchItems = [];
searchItems.push(data.props['0']);
console.log(searchItems);
}
答案 0 :(得分:0)
您可以使用流:
// if multiple search values:
const items = {
search: {
values: ['car', 'door', 'pen']
}
}
let data = {
props: []
};
data.props = [
{label: "window"},
{label: "car"},
{label: "kettle"},
{label: "chair"},
{label: "door"},
];
let matches = data.props
.map(prop => prop.label)
.filter(prop => items.search.values.indexOf(prop) >= 0);
console.log(matches);
// if one search value
let searchItem = "car";
matches = data.props
.map(prop => prop.label)
.filter(prop => searchItem === prop);
console.log(matches);
答案 1 :(得分:0)
let items = {
search: {
values: ['car', 'door', 'pen']
}
}
let data = {
props: [
{label: "window"},
{label: "car"},
{label: "kettle"},
{label: "chair"},
{label: "door"},
]
}
console.log(data.props.filter(prop => items.search.values.indexOf(prop.label) >= 0));
日志输出为:
[0]: {label: "car"}
[1]: {label: "door"}