Hi I have an object array like below
[{
one:{
a:1,
b:2
},
two:{
x:3,
y:4
}
},
{
three:{
i:5,
j:8
}
}]
I want the output like below
{one:[a,b],
two:[x,y],
three:[i,j]}
I've tried using Object.keys, map and all. I am confused. Could anyone suggest me the best way to get this.
3 Answers 3
I would use reduce and extend the value of the initial object
function extend(target) {
Array.prototype.slice.call(arguments, 1).forEach(function(source) {
source && Object.getOwnPropertyNames(source).forEach(function(name) {
if (typeof source[name] === 'object' && target[name]) {
extend.call(target, target[name], source[name]);
} else {
target[name] = source[name];
}
});
});
return target;
}
var a = [{
one:{
a:1,
b:2
},
two:{
x:3,
y:4
}
},
{
three:{
i:5,
j:8
}
}];
var b = a.reduce(function (element, created) {
return extend(created, element);
}, {});
console.log(b); //{three:[i:5,j:8], one:[a:1,b:2], two:[x:3,y:4]}
answered Aug 30, 2016 at 8:32
dievardump
2,51318 silver badges21 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
See the response below using array reduce function to reduce the existing array to object
var temp = [{
one:{
a:1,
b:2
},
two:{
x:3,
y:4
}
},
{
three:{
i:5,
j:8
}
}].reduce(function(obj , val){
Object.keys(val).forEach(function(subkey){
obj[subkey] = [].concat(Object.keys(val[subkey]))
});return obj;
} , {});
console.log(temp)
Comments
You my also try this approach where source is the input:
source.map(function(item){
var keys = Object.keys(item);
return keys.reduce(function(p, c, index){
var subKeys = Object.keys(item[c]);
console.log(item[c]);
p[c] = subKeys.map(function(subKey){
var result = {};
result[subKey] = item[c][subKey];
return result;
});
return p;
}, {});
});
answered Aug 30, 2016 at 8:44
Dhananjaya Kuppu
1,3329 silver badges10 bronze badges
Comments
lang-js
[a:1,b:2]is not JavaScript. Consequently, there is no way to get such a result.