首页 > 解决方案 > 如何在javascript中向数组添加新的键和值?

问题描述

我有两个数组,假设有以下数组值:“

var array1 = [
{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265", Name: "testing"},
{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi"},
{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},
{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},
{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}
] 

第二个数组是:

var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]

现在我想在 array1 中添加一个新的键值,仅在那些值等于数组 1 的对象中。换句话说,想要匹配两个数组并想要在具有相同值的数组中添加“status = true”。

要添加的新键是:

{status: true}

现在我的新数组应该是:

[
{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265", Name: "testing", status: true},
{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi", status: true},
{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},
{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},
{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}

]

希望你能理解。

提前致谢,

标签: javascriptarraysfilter

解决方案


你可以像这样使用forEachfind

let array1=[{Id:"809cd136-02c7-4cc8-b9de-04fd3359b265",Name:"testing"},{Id:"609d3a78-8f7c-4843-acdb-2dcfc73c0d96",Name:"Delhi"},{Id:"264d54cb-b104-48ed-91db-673327ae8d0e",Name:"rohit-auditor"},{Id:"ce9691b3-dc55-4d30-baf4-7987c2b49b3e",Name:"test"},{Id:"284e9e98-8ed7-4fb7-b09f-5d1f2a668b15",Name:"aman"}],
    array2=["809cd136-02c7-4cc8-b9de-04fd3359b265","609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
    
array2.forEach(id => {
  let found = array1.find(a => a.Id === id);
  if(found)
    found.status = true
})

console.log(array1)

if检查用于检查Idin是否array2存在于array1. 如果每个Idin都array2存在于 中array1,您可以简单地将其更改为:

array1.find(a => a.Id === id).status = true

推荐阅读