1

I have two object maps;

var one = { '1': { id: 1, pid: 1, name: 'John'},
        '3': { id: 35, pid: 3, name: 'Josh'},
        '5': { id: 34, pid: 5, name: 'Joe'} }

var two = {1:1, 34:1, 35:1}

Object.keys(one).forEach(function(item){
    two[one[item].id]= {pid : one[item]};
});

I want result as

{1:  { '1': { id: 1, pid: 1, name: 'John'}, 34: {'3': { id: 34, pid: 3, name: 'Josh'}}, 35:{'5': { id: 35, pid: 5, name: 'Joe'}}}

But I'm getting

 {1:  { pid: { id: 1, pid: 1, name: 'John'}, 34: {pid: { id: 34, pid: 3, name: 'Josh'}}, pid:{'5': { id: 35, pid: 5, name: 'Joe'}}}

But i'm not getting dynamic pid , only stack pids. I know above loop sets it in static id, want to solve it to get dynamic pid.

user3803784
  • 61
  • 1
  • 4

4 Answers4

2

To get the good result, just set the "pid" as a key like you did for the "id":

var one = { '1': { id: 1, pid: 1, name: 'John'},
        '3': { id: 35, pid: 3, name: 'Josh'},
        '5': { id: 34, pid: 5, name: 'Joe'} }

var two = {}

Object.keys(one).forEach(function(item){
    var current = one[item]
    // We initialize empty object
    two[current.id]= {}
     // We set the object at key .pid to what is wanted
    two[current.id][current.pid] = current
})

console.log(two)

Result (in JSON):

{"1":{"1":{"id":1,"pid":1,"name":"John"}},"34":{"5":{"id":34,"pid":5,"name":"Joe"}},"35":{"3":{"id":35,"pid":3,"name":"Josh"}}} 
Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
0

What you said you want isn't a valid object. My guess is that you want

var one = {
    1: { id: 1, pid: 1, name: 'John'},
    3: { id: 35, pid: 3, name: 'Josh'},
    5: { id: 34, pid: 5, name: 'Joe'}
}, two = {};
Object.keys(one).forEach(function(item){
    two[one[item].id]= one[item];
});
Oriol
  • 274,082
  • 63
  • 437
  • 513
0
var one = { 
    '1': { id: 1, pid: 1, name: 'John'},
    '3': { id: 35, pid: 3, name: 'Josh'},
    '5': { id: 34, pid: 5, name: 'Joe'} 
}

var two = {1:1, 34:1, 35:1}

Object.keys(one).forEach(function(item){
    var obj = {};
    obj[one[item].pid] = one[item];
    two[one[item].id]= obj;
});

console.log (two);
Tom
  • 4,612
  • 4
  • 32
  • 43
0

This should work for you.

var one = { '1': { id: 1, pid: 1, name: 'John'},
    '3': { id: 35, pid: 3, name: 'Josh'},
    '5': { id: 34, pid: 5, name: 'Joe'} };

var two = {1:1, 34:1, 35:1};

for (key in one){
   var item = one[key];
   two[item.id] = {};
   two[item.id][item.pid] = item;
}
Mritunjay
  • 25,338
  • 7
  • 55
  • 68