删除对象JS中的节点

时间:2015-12-09 15:21:46

标签: javascript arrays object attributes

我有以下内容:

[{
  'another@exemple.org': {
    'age': 42,
    'prefered_color': 'blue',
    'hate': 'flowers'
  }
}, {
  'another@exemple.org': {
    'age': 45,
    'prefered_color': 'red',
    'hate': 'burgers'
  }
}]

我想将关键变量(电子邮件地址)放到同一级别以获得以下内容:

[{
    'email': 'another@exemple.org',
    'age': 42,
    'prefered_color': 'blue',
    'hate': 'flowers'
  },

  {
    'email': 'another@exemple.org',
    'age': 42,
    'prefered_color': 'blue',
    'hate': 'flowers'
  }
]

我尝试了不同的东西(地图,消费),但实际上我想知道获得上述结果的最有效方法是什么。

感谢您的讨论。

1 个答案:

答案 0 :(得分:2)

使用.map() method创建一个新数组,并通过获取对象的键来检索电子邮件值:

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

实施例



var array = [{
  'another@exemple.org': {
    'age': 42,
    'prefered_color': 'blue',
    'hate': 'flowers'
  }
}, {
  'another@exemple.org': {
    '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>
&#13;
&#13;
&#13;