$scope.Array1= [{
Name: 'Alzheimers',
Value: 1,
Selected: false
}, {
Name: 'Arthritis',
Value: 2,
Selected: false
},{
Name: 'Cancer',
Value: 3,
Selected: false
}{
Name: 'Cellulitis',
Value: 4,
Selected: false
}
];
$scope.Array2=[1,3];
我希望结果像
$scope.Array1= [{
Name: 'Alzheimers',
Value: 1,
Selected: true
}, {
Name: 'Arthritis',
Value: 2,
Selected: false
},{
Name: 'Cancer',
Value: 3,
Selected: true
}{
Name: 'Cellulitis',
Value: 4,
Selected: false
}
];
selected
对象变量(Alzheimers,Cancer)
从Array2
更新为true? 如果你提出没有循环的建议,那对我来说会很棒。
答案 0 :(得分:3)
使用Array#forEach对array1
进行迭代,检查Value
中是否包含Array2
,并将结果分配给Selected
属性。该解决方案将改变原始对象。
const array1 = [{"Name":"Alzheimers","Value":1,"Selected":false},{"Name":"Arthritis","Value":2,"Selected":false},{"Name":"Cancer","Value":3,"Selected":false},{"Name":"Cellulitis","Value":4,"Selected":false}];
const array2 = [1, 3];
array1.forEach((o) => o.Selected = array2.includes(o.Value));
console.log(array1);

如果您想要一个包含新对象的新数组,请使用Array#map,使用Object#assign。
let array1 = [{"Name":"Alzheimers","Value":1,"Selected":false},{"Name":"Arthritis","Value":2,"Selected":false},{"Name":"Cancer","Value":3,"Selected":false},{"Name":"Cellulitis","Value":4,"Selected":false}];
const array2 = [1, 3];
array1 = array1.map((o) => array2.includes(o.Value) ? Object.assign({}, o, {
Selected: true
}) : o);
console.log(array1);

答案 1 :(得分:0)
您可以使用forEach
let array1 =
[
{"Name":"Alzheimers","Value":1,"Selected":false},
{"Name":"Arthritis","Value":2,"Selected":true},
{"Name":"Cancer","Value":3,"Selected":false},
{"Name":"Cellulitis","Value":4,"Selected":false}
];
let array2 = [1, 3];
array1.forEach(x => x.Selected = array2.indexOf(x.Value) != -1);
console.log(array1);