admin管理员组文章数量:1414628
Lets say I have the following array structure:
"stores" : [
{
id: 1,
name: 'lopd',
},
{
id: 2,
name: 'abc'
}
]
And I want to change the parameter names to following:
"stores" : [
{
value: 1,
label: 'lopd',
},
{
value: 2,
label: 'abc'
}
]
How would I do this in ES6?
Lets say I have the following array structure:
"stores" : [
{
id: 1,
name: 'lopd',
},
{
id: 2,
name: 'abc'
}
]
And I want to change the parameter names to following:
"stores" : [
{
value: 1,
label: 'lopd',
},
{
value: 2,
label: 'abc'
}
]
How would I do this in ES6?
Share Improve this question edited Jan 9, 2018 at 20:45 Sébastien 12.1k12 gold badges59 silver badges82 bronze badges asked Jan 9, 2018 at 13:21 JoelgullanderJoelgullander 1,6842 gold badges22 silver badges51 bronze badges 2- do you like to keep the objects and the array, or could it be a new array with new objects? – Nina Scholz Commented Jan 9, 2018 at 13:25
- @NinaScholz new array with new objects works, its just for presentational purpose – Joelgullander Commented Jan 9, 2018 at 13:28
4 Answers
Reset to default 5You could use a destructuring assignment with an object property assignment pattern and short hand properties.
var stores = [{ id: 1, name: 'lopd' }, { id: 2, name: 'abc' }];
stores = stores.map(({ id: value, name: label }) => ({ value, label }));
console.log(stores);
You could do the following by using the map
function:
let example = {
"stores" : [
{
id: 1,
name: 'lopd',
},
{
id: 2,
name: 'abc'
}
]
}
let answer = example.stores.map(item => {
return {
value: item.id,
label: item.name
}
})
console.log(answer)
Just for the sake of pleteness, although I would actually use Nina's answer: if you want to actually modify the original objects, you can create new properties and delete
the ones you want to discard.
var obj = {
stores: [{
id: 1,
name: 'lopd',
},
{
id: 2,
name: 'abc'
}
]
}
console.log(obj.stores);
obj.stores.forEach(function(val) {
val.value = val.id;
val.label = val.name;
delete val.id;
delete val.name;
});
console.log(obj.stores);
It may not matter much (or at all most of the time) but this is the only way to preserve the original object. Other solutions replace the entire objects in the array by a new one...
Also: this is ES5 so it will work in older browsers (namely IE9)
You may also create a new array using:
Array.from()
Arrow Functions
Example:
var data = [{id: 1, name: 'lopd'}, {id: 2, name: 'abc'}];
var result = Array.from(data, obj => ({value: obj.id, label: obj.name}));
console.log(result);
本文标签: javascriptchange names of object parameters in arrayStack Overflow
版权声明:本文标题:javascript - change names of object parameters in array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745164675a2645615.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论