Javascript动态创建对象数组

时间:2017-10-16 10:44:42

标签: javascript arrays json object

我有JSON回复,即

[{"name":"title","value":"STEP-01","translation":"STEP-01"},{"name":"meta_description","value":"","translation":"meta desc"}, ......]

从此我想动态创建一个对象数组,以便我将name作为键,translation作为值 喜欢

data.en = {
  title : 'STEP-01',
  meta-description :     meta desc
}

我试过这个,但它创建了一个数组

jsonObj = []

$.each(result, function (index, value) {

             lang_array =   {};
            lang_array[value.name]  =   value.translation;
            jsonObj.push(lang_array);

        })

1 个答案:

答案 0 :(得分:0)

根据您的示例,您正在尝试创建JS对象,而不是数组。

选项1 :使用Array#reduce收集每个对象的名称和翻译为新对象:

const data = [{"name":"title","value":"STEP-01","translation":"STEP-01"},{"name":"meta_description","value":"","translation":"meta desc"}];

const result = data.reduce((r, { name, translation }) => {
  r[name] = translation;
  
  return r;
}, {});

console.log(result);

选项2 :使用Array#map创建包含属性和值的对象集合,并使用Object#assign和{{3将它们组合到单个对象}}:

const data = [{"name":"title","value":"STEP-01","translation":"STEP-01"},{"name":"meta_description","value":"","translation":"meta desc"}];

const result = Object.assign(...data.map(({ name, translation }) => ({ [name]: translation })));

console.log(result);