1

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.

1
  • 1
    [a:1,b:2] is not JavaScript. Consequently, there is no way to get such a result. Commented Aug 30, 2016 at 8:33

3 Answers 3

2

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]}
Sign up to request clarification or add additional context in comments.

Comments

1

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

0

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;
     }, {});
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.