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);