I have an array of Objects
[{"a":{"name":"abc","age":2}},
{"b":{"name":"xyz","age":3}},
{"c":{"name":"pqr","age":4}}]
I need to convert this to
[{"name":"abc","age":2},
{"name":"xyz","age":3},
{"name":"pqr","age":4}]
I have an array of Objects
[{"a":{"name":"abc","age":2}},
{"b":{"name":"xyz","age":3}},
{"c":{"name":"pqr","age":4}}]
I need to convert this to
[{"name":"abc","age":2},
{"name":"xyz","age":3},
{"name":"pqr","age":4}]
Share
Improve this question
edited Mar 19, 2018 at 11:20
James Jones
3,8995 gold badges27 silver badges45 bronze badges
asked Mar 19, 2018 at 10:36
ErickErick
1,14611 silver badges24 bronze badges
4
- 2 Wele to StackOverflow! Have you tried anything so far? StackOverflow isn't a free code-writing service and expects you to try to solve your own problem first. Please update your question to show what you have already tried, showcasing a specific problem you are facing in a minimal, plete, and verifiable example. For further information, please see how to ask a good question, and take the tour of the site. – palaѕн Commented Mar 19, 2018 at 10:37
- @SandipND it does'nt work with JSON.stringify() – Erick Commented Mar 19, 2018 at 10:42
- 1 Please share your attempt. – gurvinder372 Commented Mar 19, 2018 at 10:43
- @SandipND : It worked when I added JSON.stringify() – Erick Commented Mar 19, 2018 at 11:10
4 Answers
Reset to default 6Simply use map
and Object.values
var output = arr.map( s => Object.values(s)[0] );
Demo
var arr = [{
"a": {
"name": "abc",
"age": 2
}
},
{
"b": {
"name": "xyz",
"age": 3
}
},
{
"c": {
"name": "pqr",
"age": 4
}
}
];
var output = arr.map( s => Object.values(s)[0] );
console.log(output);
const array = [{"a":{"name":"abc","age":2}},
{"b":{"name":"xyz","age":3}},
{"c":{"name":"pqr","age":4}}]
array.map(item=>{
return Object.keys(item).reduce((acc,key)=>{
return item[key]
},{})
})
And straight ahead dumb way as well:
src=[{"a":{"name":"abc","age":2}},
{"b":{"name":"xyz","age":3}},
{"c":{"name":"pqr","age":4}}]
result=[]
for arr in src:
for d in arr:
result.append(arr[d])
You can use one of Array.prototype iteration methods, like map
or reduce
. I prefer reduce
for such kind of problems. Array.prototype.reduce
takes the second parameter as a default value, so it's an empty array and for every iteration that array is concatenated with the value of an object e.g. { a: { name: "abc", age: 2 } }
will lead to adding { name: "abc", age: 2 }
to the resulted array.
const input = [
{ a: { name: "abc", age: 2 } },
{ b: { name: "xyz", age: 3 } },
{ c: { name: "pqr", age: 4 } }
];
const output = input.reduce(
(acc, entry) => acc.concat(Object.values(entry)),
[]
)
console.log(output)