I have an object called ‘times’, that holds another object called ‘20102’, that holds a list of 3 objects. It looks like this:
JavaScript
x
8
1
times: {
2
20102: [
3
{ name:'jane', age:12 },
4
{ name:'josh', age:19 },
5
{ name:'jill', age:14 },
6
]
7
}
8
However, what I want it to look like is this:
JavaScript
1
6
1
times:[
2
{ name:'jane', age:12 },
3
{ name:'josh', age:19 },
4
{ name:'jill', age:14},
5
]
6
I was thinking of doing a double for loop but that’s not efficient. What’s a better way?
Advertisement
Answer
using Object.values() and flat()
JavaScript
1
17
17
1
var x = {
2
times: {
3
20102: [{
4
'key': '1'
5
},
6
{
7
'key': '2'
8
},
9
{
10
'key': '3'
11
},
12
]
13
}
14
};
15
x.times = Object.values(x.times).flat();
16
17
console.log(x);
If you know there will only be one key
JavaScript
1
17
17
1
var x = {
2
times: {
3
20102: [{
4
'key': '1'
5
},
6
{
7
'key': '2'
8
},
9
{
10
'key': '3'
11
},
12
]
13
}
14
};
15
x.times = Object.values(x.times)[0];
16
17
console.log(x);