简体   繁体   English

替换 Javascript 对象中的属性值

[英]Replace attribute value in a Javascript Object

I have an array in this format:我有一个这种格式的数组:

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

What I want is to replace every id value with null.我想要的是用 null 替换每个 id 值。 My first idea would have been to build a regex im combination with a for loop.我的第一个想法是构建一个带有 for 循环的正则表达式 im 组合。 But is there maybe a more efficient way to do this?但是有没有更有效的方法来做到这一点?

See map method.地图方法。

 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)

Read through documentation :通读文档

The RegExp object is used for matching text with a pattern. RegExp 对象用于将文本与模式匹配。

Here, working with regex would be really unefficient since you work with objects在这里,使用正则表达式会非常低效,因为您使用的是对象


There are multiple ways of doing what you want :有多种方法可以做你想做的事:

You can use a for i loop to loop through your items您可以使用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)

Or with the Array#forEach method on arrays :或者使用数组上的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)


You could also have used Array#Map您也可以使用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