user2829131
user2829131

Reputation:

Remove nodes in object JS

I have the following:

[{
  '[email protected]': {
    'age': 42,
    'prefered_color': 'blue',
    'hate': 'flowers'
  }
}, {
  '[email protected]': {
    'age': 45,
    'prefered_color': 'red',
    'hate': 'burgers'
  }
}]

I want to put the key variable (email address) to the same level to get the following:

[{
    'email': '[email protected]',
    'age': 42,
    'prefered_color': 'blue',
    'hate': 'flowers'
  },

  {
    'email': '[email protected]',
    'age': 42,
    'prefered_color': 'blue',
    'hate': 'flowers'
  }
]

I tried different things (map, expends) but I am actually wondering what is the most efficient way to get the result above.

Thank you for discussing.

Upvotes: 0

Views: 25

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241178

Create a new array using the .map() method and retrieve the email value by getting the key of the object:

var newArray = array.map(function(obj) {
  var key = Object.keys(obj);
  obj[key].email = key[0];
  return obj[key];
});

Example:

var array = [{
  '[email protected]': {
    'age': 42,
    'prefered_color': 'blue',
    'hate': 'flowers'
  }
}, {
  '[email protected]': {
    'age': 45,
    'prefered_color': 'red',
    'hate': 'burgers'
  }
}];

var newArray = array.map(function(obj) {
  var key = Object.keys(obj);
  obj[key].email = key[0];
  return obj[key];
});

document.querySelector('pre').textContent = JSON.stringify(newArray, null, 4);
<pre></pre>

Upvotes: 2

Related Questions