-1

I have this object:

obj = {key : val,
      key1 : val1,
      key2 : {key21 : val21,key22 : val22},
      key3 : val3}

I want to generate a new object to be like:

objnew = {key : val,
         key1 : val1,
         key21 : val21,
         key22 : val22,
         key3 : val3}
Mamun
  • 66,969
  • 9
  • 47
  • 59
amira
  • 25
  • 2

3 Answers3

1

As per your comments, if you really want to keep the order for whatever reason, and don't want to do it for anything but key2, here's a possible solution.

Please read this question for information about order of object keys. In short, it's most likely a bad idea to rely on it in most cases. You'd be better off using a Map instance or just an array.

let obj = {
  key: 0,
  key1: 1,
  key2: {key21: 21, key22: 22},
  key3: 3
};

let objArray = Object.keys(obj).map(key => ({key, value: obj[key]}));

let result = objArray.reduce((result, entry) => 
  Object.assign(result, entry.key === 'key2' ? entry.value : {[entry.key]: entry.value})
, {});

console.log(result);
Jeto
  • 14,596
  • 2
  • 32
  • 46
0

For 2-level object structure (with Object.keys() and Object.assign() functions):

var obj = {
  'key' : 'val',
  'key1' : 'val1',
  'key2' : {'key21' : 'val21', 'key22' : 'val22'},
  'key3' : 'val3'
};

Object.keys(obj).forEach(function(k){
    if (typeof obj[k] === 'object') {
        Object.assign(obj, obj[k]);
        delete obj[k];
    }
});
  
console.log(obj);
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • this will push the new values at the end of the object. I need to keep it arranged. – amira Mar 18 '18 at 00:07
  • also I just need to do this for key2 value not to apply this on the full object. just replace key2 by it's 2nd level object keys and valye – amira Mar 18 '18 at 00:08
  • @amira, *I need to keep it arranged* - you can not, objects are unordered structures – RomanPerekhrest Mar 18 '18 at 00:11
0

Here you go:

var obj = {
  key : 1,
  key1 : 2,
  key2 : { key21 : 3,key22 : 4 },
  key3 : 5
};

Object.keys(obj).forEach(function(key) {
 if(typeof obj[key] === 'object') {
    Object.keys(obj[key]).forEach(function(innerKey) {
      obj[innerKey] = obj[key][innerKey];
    });
    delete  obj[key];
  }
});
console.log(obj);
Joe Hany
  • 1,015
  • 1
  • 8
  • 14
  • this will push the new values at the end of the object. I need to keep it arranged. also, I just need to do this for key2 value not to apply this to the full object. just replace key2 by it's 2nd level object keys and value – amira Mar 18 '18 at 00:09
  • @amira I think there is on way to order object properties in javascript. you can use an array if order is important to you. – Joe Hany Mar 18 '18 at 00:21