我有两个对象数组,如下所示:
const data = [
{
id: 1,
condition: 1,
helpers: [{id: 1, condition: null}, {id: 2, condition: 2}]
},
{
id: 2,
condition: null,
helpers: [{id: 1, condition: 1}, {id: 2, condition: null}]
}
]
const conds = [
{
id: 1,
conditions: {
rules: ['test', 'foo']
}
},
{
id: 2,
conditions: {
rules: ['#hashtag', 'foo']
}
}
]
我试图实现的是,我想用condition
数组中的data
数组替换conds
数组的let newArray = [];
data.forEach(obj => {
conds.forEach(cond => {
if (obj.condition) {
if (obj.condition === cond.id) {
obj.condition = cond.conditions.rules;
newArray.push(obj);
}
} else {
obj.helpers.forEach(h => {
if (h.condition && h.condition === cond.id) {
h.condition = cond.conditions.rules;
newArray.push(obj);
}
});
}
})
});
值。
我的解决方案效果不好看起来像这样:
newArray
我觉得我非常接近解决方案,因为我的condition
包含更改属性,但不包含帮助程序内的最后一项,而[
{
id: 1
condition: ['test', 'foo'],
helpers: [{id: 1, condition: null}, {id: 2, condition: ['#hashtag', 'foo']}]
},
{
id: 2
condition: null,
helpers: [{id: 1, condition: ['test', 'foo']}, {id: 2, condition: null}]
},
]
属性仍然是2。
输出应如下所示:
const data = [
{
id: 1,
condition: 1,
helpers: [{id: 1, condition: null}, {id: 2, condition: 2}]
},
{
id: 2,
condition: null,
helpers: [{id: 1, condition: 1}, {id: 2, condition: null}]
}
]
const conds = [
{
id: 1,
conditions: {
rules: ['test', 'foo']
}
},
{
id: 2,
conditions: {
rules: ['#hashtag', 'foo']
}
}
]
// START SOLUTION
const rulesMap = conds.reduce((map, condition) => {
map[condition.id] = condition.conditions.rules;
return map;
}, {});
const finalData = data.map(dataItem => {
dataItem.condition = dataItem.condition ? rulesMap[dataItem.condition] : null;
return dataItem;
});
// END SOLUTION
console.log(finalData);
我在这里错过了什么?
const rulesMap = conds.reduce((map, condition) => {
map[condition.id] = condition.conditions.rules;
return map;
}, {});
创建条件地图:
const finalData = data.map(dataItem => {
dataItem.condition = dataItem.condition ? rulesMap[dataItem.condition] : null;
return dataItem;
});
获取已更换条件规则的新数据列表:
data
使用forEach
循环通过id
数组获取conds
然后使用find()
过滤conditions.rules
数组以获得相关的data.forEach(function(item) {
item.condition = conds.find(x => x.id === item.id).conditions.rules;
});
,如:
const data = [{
id: 1,
condition: 1,
helpers: [{id: 1, condition: null}, {id: 2, condition: 2}]
},{
id: 2,
condition: null,
helpers: [{id: 1, condition: 1}, {id: 2, condition: null}]
}];
const conds = [{
id: 1,
conditions: {
rules: ['test', 'foo']
}
},{
id: 2,
conditions: {
rules: ['#hashtag', 'foo']
}
}];
data.forEach(function(item) {
item.condition = conds.find(x => x.id === item.id).conditions.rules;
});
console.log(data);
工作小提琴:
const finalData = data.map(dataItem => {
dataItem.condition = dataItem.condition ? rulesMap[dataItem.condition] : null;
dataItem.helpers.map(item => {
item.condition = item.condition ? rulesMap[item.condition] : null
})
return dataItem;
});
搞定了:
qazxswpoi