javascript - 如何在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"}
]
希望你能理解。
提前致谢,
解决方案
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
检查用于检查Id
in是否array2
存在于array1
. 如果每个Id
in都array2
存在于 中array1
,您可以简单地将其更改为:
array1.find(a => a.Id === id).status = true
推荐阅读
- fullcalendar - 如何在完整日历资源视图中阻止日期?
- flutter - Flutter GridView 占用所有屏幕空间?
- javascript - 使用功能组件输入 ReactJS
- javascript - 如何使用 Selenium Java 框架自动化 Shadow DOM
- c++ - 我们什么时候应该编写自己的移动构造函数(移动赋值运算符)
- arrays - 有没有办法在 C 语言的表格形式输出期间处理空格?
- pytorch - sqrt_vml_cpu 未针对“长”实现
- python - 在Python中引用子目录之间文件的正确方法和VSCode设置是什么
- postgresql - 如何使用 date_part 函数将每月的值拆分为每天和国家
- javascript - 是否有可用于 node.js 的 array_walk_recursive php 函数的替代方法?