英文:
How to change the array object property values javascript
问题 {#heading}
let arrObj = [
{ name: "Test1", status: true },
{ name: "Test2", status: false },
{ name: "Test3", status: true }
]
let arr = ["Test1", "Test3"];
for (k of arr) {
if (arrObj.name == k) {
arrObj.status = true;
}
}
console.log(arrObj);
英文:
I have one array object and one array. what are the values in that array that value matched in the array object need to change the status like true.
arrObj
output should be like below:
[
{ name: "Test1", status: true },
{ name: "Test2", status: false },
{ name: "Test3", status: true }
]
Demo: https://stackblitz.com/edit/github-7plax5-mu3l6a?file=src%2Fapp%2Fapp.component.ts
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let arrObj = [{
name: "Test1",
status: true
},
{
name: "Test2",
status: true
},
{
name: "Test3",
status: true
}
]
let arr = \[\"Test1\", \"Test3\"\];
for (k of arr) {
if (arrObj.name == k) {
arrObj.status = true;
}
}
`console.log(arrObj);
`
<!-- end snippet -->
答案1 {#1}
得分: 1
修改原始数组的最简单方法如下:
arrObj.forEach(item => item.status = arr.includes(item.name));
console.log(arrObj);
Typescript版本 运行与我已经发布的相同的脚本,具有推断的类型。 英文:
Simplest method to modify the original array
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
arrObj.forEach(item => item.status = arr.includes(item.name))
`console.log(arrObj);
`
<!-- language: lang-html -->
<script>
let arrObj = [{
name: "Test1",
status: false
},
{
name: "Test2",
status: false
},
{
name: "Test3",
status: false
}
]
`let arr = ["Test1", "Test3"];
</script>
`
<!-- end snippet -->
Typescript version runs the same script as I already posted with inferred types
答案2 {#2}
得分: 0
你正在迭代错误的数组。
请在arrObj
上进行迭代,然后使用indexOf()
方法检查数组是否包含该值。
let arrObj = [{
name: "Test1",
status: false
},
{
name: "Test2",
status: false
},
{
name: "Test3",
status: false
}
]
let arr = ["Test1", "Test3"];
arrObj.forEach(function(k) {
if (arr.indexOf(k.name) != -1) {
k.status = true;
}
});
console.log(arrObj)
英文:
You are iterating over the wrong array.
Iterate over arrObj
and then check if array contains that value using the indexOf()
method.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let arrObj = [{
name: "Test1",
status: false
},
{
name: "Test2",
status: false
},
{
name: "Test3",
status: false
}
]
let arr = \[\"Test1\", \"Test3\"\];
arrObj.forEach(function(k) {
if (arr.indexOf(k.name) != -1) {
k.status = true;
}
});
`console.log(arrObj)
`
<!-- end snippet -->