在JavaScript中添加对象集合的键

时间:2016-01-20 17:03:42

标签: javascript

我在JavaScript中有一组对象:

[
  {A:10},
  {B:20},
  {C:30}
]

我正在尝试将其转换为一个像这样的对象数组(与d3.js一起使用):

[
  {word: "A", weight: 10},
  {word: "B", weight: 20},
  {word: "C", weight: 30}
]

我只需执行以下操作即可获得初始对象数组:

var wordData = [];
for (var i = 0; i < words.length; i++) {
    if (wordData.hasOwnProperty(words[i])) {
        wordData[words[i]] += 1;
    } else {
        wordData[words[i]] = 1;
    }
}

这只是设置一个简单的哈希,但不会在每个哈希之前添加密钥。

修改

JSFiddle为了简单起见。

2 个答案:

答案 0 :(得分:3)

var wordData = [
  {A: 10},
  {B: 20},
  {C: 30}
];

var result = wordData.map(function (item) {
    var key = Object.keys(item)[0];
    return {word: key, weight: item[key]};
});

答案 1 :(得分:1)

尝试以下代码。我试过for循环。

var wordData =[
{A: 10},
{B: 20},
{C: 30}
];

var results = [];
for (var prop in wordData) {                    
    var key = Object.keys(wordData[prop])[0];
    result = {word: key, weight: wordData[prop][key]};
    results.push(result);
}

var json_result = JSON.stringify(results, null, 2);
console.log(json_result);

输出

[
  {
    "word": "A",
    "weight": 10
  },
  {
    "word": "B",
    "weight": 20
  },
  {
    "word": "C",
    "weight": 30
  }
]

var json_result = JSON.stringify(results); // without null
console.log(json_result);

输出

[{"word":"A","weight":10},{"word":"B","weight":20},{"word":"C","weight":30}]

<div id="data">
  Run the code below
</div>

var wordData = {}; // Edit, use {} intead of [] here.
for (var i = 0; i < words.length; i++) {
    // The problem is definitely in this loop.
  if (wordData.hasOwnProperty(words[i])) {
    wordData[words[i]] += 1;
  } else {
    wordData[words[i]] = 1;
  }
}

var results = [];
for (var prop in wordData) {  
    result = {word: prop, weight: wordData[prop]};
    results.push(result);
}
var json_result = JSON.stringify(results, null, 2);
document.getElementById('data').innerHTML = json_result;

Demo