我有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);
})
答案 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);