我想用一些预定义值(如5)更新对象值。
这是我的对象,
dataSet
预期输出;
for(data of dataSet){
console.log(data.subCategory)
}
这是我的尝试:
let data = {"a":1,"b":2,"c":3,"d":5}
答案 0 :(得分:0)
尝试使用Object.entries()
:
Object.entries()
方法返回给定对象自己的可枚举属性[key,value]对的数组,其顺序与for...in
循环所提供的顺序相同(区别在于: in循环也会枚举原型链中的属性。
let data = {"a":1,"b":2,"c":3,"d":5}
data = Object.entries(data).map(k => ({[k[0]]: k[1] * 5}))
console.log(data)
答案 1 :(得分:0)
将该值乘以5
:
let data = {"a":1,"b":2,"c":3,"d":5};
Object.keys(data).forEach(key => data[key] *= 5);
console.log(data);
使用 Object.Entries()
let data = {"a":1,"b":2,"c":3,"d":5};
Object.entries(data).forEach(([key, val]) => data[key] = val*5);
console.log(data);
答案 2 :(得分:0)
只需遍历所有新对象的键并将其更新为现有对象即可。
var obj = {"a":1,"b":2,"c":3,"d":5,"f":9,"g":11,"h":21}
var newObj = {"a":5,"b":10,"d":20,"h":25}
let keys = Object.keys(newObj)
keys.map(x=>{
obj[x] = newObj[x]
})
console.log(obj)