繁体   English   中英

替换 Javascript 对象中的属性值

[英]Replace attribute value in a Javascript Object

我有一个这种格式的数组:

var arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}]

我想要的是用 null 替换每个 id 值。 我的第一个想法是构建一个带有 for 循环的正则表达式 im 组合。 但是有没有更有效的方法来做到这一点?

地图方法。

 const source = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}]; const destination = source.map((el) => ({ ...el, id: null })); // For demo purpose console.log(destination);

 var arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}] arr.forEach(item => { Object.keys(item).forEach(function(key) { if(key ==='id') { item[key] = null; } }); }) console.log(arr)

通读文档

RegExp 对象用于将文本与模式匹配。

在这里,使用正则表达式会非常低效,因为您使用的是对象


有多种方法可以做你想做的事:

您可以使用for i循环遍历您的项目

 const arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}] for (let i=0; i<arr.length;i++){ arr[i].id = null } console.log(arr)

或者使用数组上的Array#forEach方法:

 const arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}] arr.forEach(item => { item.id = null }) console.log(arr)


您也可以使用Array#Map

 const arr = [{id: 1, age: 25, money: 2500},{id: 10, age: 10, money: 100},{id: 115, age: 80, money: 1350}] const arrWithoutIds = arr.map(item => { item.id = null return item }) console.log(arrWithoutIds)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM