admin管理员组文章数量:1327488
I would like to know how to change the value in a nested object array using javascript.
how to change the "load": "undefined"
to "load":1
in the obj
var obj=[{
"id": "service",
"country": "AR",
"load": "undefined"
},{
"id": "fund",
"country": "CA",
"load": "undefined"
}]
var result = obj.forEach(e=>e.load=1);
Expected Output:
[{
"id": "service",
"country": "AR",
"load": 1
},{
"id": "fund",
"country": "CA",
"load": 1
}]
I would like to know how to change the value in a nested object array using javascript.
how to change the "load": "undefined"
to "load":1
in the obj
var obj=[{
"id": "service",
"country": "AR",
"load": "undefined"
},{
"id": "fund",
"country": "CA",
"load": "undefined"
}]
var result = obj.forEach(e=>e.load=1);
Expected Output:
[{
"id": "service",
"country": "AR",
"load": 1
},{
"id": "fund",
"country": "CA",
"load": 1
}]
Share
Improve this question
edited Aug 3, 2019 at 14:38
Senthil
asked Aug 3, 2019 at 14:32
SenthilSenthil
1,1011 gold badge10 silver badges26 bronze badges
2
-
Why the two key names are different
load
andloading
– Maheer Ali Commented Aug 3, 2019 at 14:34 -
2
Your code works. The only issue is that
forEach
doesn't return anything - you're instead changingobj
in-place, so you can just return that, if needed. – VLAZ Commented Aug 3, 2019 at 14:37
2 Answers
Reset to default 8You can do this easily with new ES2015+ syntax. Using the spread operator:
var result = obj.map(e => ({ ...e, load: 1 }));
This will keep all the other props and only change load
to what you want.
Also, FYI - [].forEach()
does not work this way.
forEach
does not return anything,your code is working fine so in your code the original object that is obj
will be changed and if you log it show load:1
. If you don't want to change original array use map which returns a new array
var obj = [{
"id": "service",
"country": "AR",
"load": "undefined"
}, {
"id": "fund",
"country": "CA",
"loading": "undefined"
}]
var result = obj.map(function(elem) {
return Object.assign({}, elem, {
// only change to 1 if value is undefined
load: elem.load === 'undefined' ? 1 : elem.load
})
});
console.log(result)
本文标签: How to change key value in the nested object array javascriptStack Overflow
版权声明:本文标题:How to change key value in the nested object array javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742201034a2431963.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论