I have an array like this:
[
{
0 : {
id: 'somevalue',
name: 'John Doe',
age: '20'
}
}
...
]
I would like to modify the array, for example to set the key to the id
attribute like this:
[
{
somevalue : {
name: 'John Doe',
age: '20'
}
}
]
What would be the best way to achieve this. Thanks for your time.
I have an array like this:
[
{
0 : {
id: 'somevalue',
name: 'John Doe',
age: '20'
}
}
...
]
I would like to modify the array, for example to set the key to the id
attribute like this:
[
{
somevalue : {
name: 'John Doe',
age: '20'
}
}
]
What would be the best way to achieve this. Thanks for your time.
Share Improve this question asked May 22, 2020 at 10:40 realnsleorealnsleo 7072 gold badges12 silver badges33 bronze badges 1-
data.map(function(d) { let ref = d[0]; let id = ref.id; delete ref.id; return { [id]: ref }; })
– Rayon Commented May 22, 2020 at 10:45
5 Answers
Reset to default 5You could destructure the object and take the wanted key out of the object. Then return new object with wanted value.
var array = [{ 0 : { id: 'somevalue', name: 'John Doe', age: '20' } }],
key = 'id',
result = array.map(({ 0: { [key]: k, ...o } }) => ({ [k]: o }));
console.log(result);
Assuming there is only one nested object, you can use the function map
as follow:
let arr = [
{
0 : {
id: 'somevalue',
name: 'John Doe',
age: '20'
}
}
];
let result = arr.map(o => {
let [{id, ...rest}] = Object.values(o);
return {[id]: rest};
});
console.log(result);
I guess you have just more then 1 Object. You can try it like this.
let data = [
{
0 : {
id: 'somevalue',
name: 'John Doe',
age: '20'
}
}
]
let result = data.map((el, index) => {
let id = el[index].id;
delete el[index].id;
return { [id]: {...el[index]}}
})
console.log(result);
You can try this if the key is always '0' in the given object
const arr = [
{
0 : {
id: 'somevalue',
name: 'John Doe',
age: '20'
}
}
]
arr.map(item => {
const value = {...item[0]};
const key = value.id;
delete value.id;
return {
[key]: value
}
})
You can use map
and reduce
functions to achieve the desired output.
This solution will work even if you have more than one nested objects and if you have more properties in your nested objects, i.e. properties other than name
and age
const arr = [
{
0: { id: "somevalue", name: "John Doe", age: "20" },
1: { id: "somevalue 2", name: "John Doe", age: "20", gender: 'male' }
},
{
0: { id: "somevalue 3", name: "John Doe", age: "20" },
1: { id: "somevalue 4", name: "John Doe", age: "20", gender: 'male' },
2: { id: "somevalue 5", name: "John Doe", age: "20" }
}
];
const res = arr.map((obj) => {
const v = Object.values(obj);
return v.reduce((acc, curr) => {
const {id, ...restProps } = curr;
acc[curr.id] = restProps;
return acc;
}, {});
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }