Reputation: 21
I have this json
below:
[
{"animal": "cat"},
{"animal": "dog"},
{"animal": "elephant"},
{"vehicle": "car"},
{"vehicle": "bike"},
{"vehicle": "truck"},
{"toys": "a1"},
{"toys": "a2"},
{"toys": "a3"}
]
My expected json response is:
[
{"animal": "cat", "vechile": "car", "toys": "a1"},
{"animal": "dog", "vechile": "bike", "toys": "a2"},
{"animal": "elephant", "vechile": "truck", "toys": "a3"}
]
I tried the following program but didn't give me the expected output, I wanted to make an array where I could compare it and add accordingly:
var myGlobalArr = []
var globalObject = {}
for (var i = 0; i < mainArr.length; i++)
{
if (Object.keys(mainArr[i])[0] == Object.keys(myGlobalArr[i])[0])
{
globalObject[Object.keys(mainArr[i])[0]] = globalObject[Object.values(mainArr[i])[0]]
}
}
console.log(myGlobalArr)
HELP WOULD BE APPRECIATED!!
#EDITED:
It is going to be block of 3
.
Upvotes: 2
Views: 113
Reputation: 386560
You could take a hash table which takes care of the right index of the same key for the result set.
This works for an arbitrary count of objects/properties and order, as long as the same properties are in order.
var data = [ { animal: "cat" }, { animal: "dog" }, { animal: "elephant" }, { vehicle: "car" }, { vehicle: "bike" }, { vehicle: "truck" }, { toys: "a1" }, { toys: "a2" }, { toys: "a3" }],
indices = {},
result = data.reduce((r, o) => {
var key = Object.keys(o)[0];
indices[key] = indices[key] || 0;
Object.assign(r[indices[key]] = r[indices[key]] || {}, o);
indices[key]++;
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 17190
You can do this using Array.reduce(). On every iteration of reduce
you can check to what index of the final array put your data using the current index of the object modulus
3 (idx % 3
):
const input = [
{"animal": "cat"},
{"animal": "dog"},
{"animal": "elephant"},
{"vehicle": "car"},
{"vehicle": "bike"},
{"vehicle": "truck"},
{"toys": "a1"},
{"toys": "a2"},
{"toys": "a3"}
];
let res = input.reduce((acc, curr, idx) =>
{
let [[k, v]] = Object.entries(curr);
acc[idx % 3] = acc[idx % 3] || {};
acc[idx % 3][k] = v;
return acc;
}, [])
console.log(res);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
Upvotes: 1