在json中声明动态键(javascript,node)

时间:2017-04-11 00:03:35

标签: javascript arrays json node.js

我有一个对象数组,每个对象类似于:

{ word: 'intentional',
  definition: 'done by intention or design',
  type: 'adjective',
  Synonyms: [  'conscious', 'deliberate', 'intended', 'knowing', ] }

我正在尝试将整个数组转换为以下json格式:

{
    "conscious": {
        "data": ["done by intention or design"],
        "type": "adjective",
        "Synonym For": ["intentional"]
    },
    "deliberate": {
        "data": ["done by intention or design"],
        "type": "adjective",
        "Synonym For": ["intentional"]
    },
    ...

}

这个json格式是另一个程序的输入,我无法控制。 我在node.js上运行它。

如何声明一个对象然后循环遍历数组以按预期填充它?

2 个答案:

答案 0 :(得分:2)

var obj = { word: 'intentional',
  definition: 'done by intention or design',
  type: 'adjective',
  Synonyms: [ 'conscious', 'deliberate', 'intended', 'knowing' ] },
  
  res = obj.Synonyms.reduce(function(s,a) {
    s[a] = { data: [obj.definition], type: obj.type, SynonymFor: [obj.word] };
    return s;
  }, {});
  
  console.log(res);

答案 1 :(得分:2)

var jsonObj = {};
wordArray.forEach((word) => {
    word.Synonyms.forEach((synonym) => {
        jsonObj[synonym] = {
            data: [word.definition],
            type: word.type,
            'Synonym For': [word.word]
        };
    })
})