我有以下数组对象:
var data = [
{id:'value.id_1', name: 'value.name_1', type: 'value.type_1', value: 'value.value_1'},
{id:'value.id_2', name: 'value.name_2', type: 'value.type_2', value: 'value.value_2'},
{id:'value.id_3', name: 'value.name_3', type: 'value.type_3', value: 'value.value_3'},
]
,我想创建一个像这样的新数组对象:
var request = [
{
"value.id_1" : "value.value_1",
"value.id_2" : "value.value_2",
"value.id_3" : "value.value_3",
}
]
如何进行呢?
私下
答案 0 :(得分:3)
迭代数据数组,然后在新对象中分配id
value
。
注意:对象键不能相同。
var data = [
{id:'value.id', name: 'value.name', type: 'value.type', value: 'value.value'},
{id:'value.id2', name: 'value.name2', type: 'value.type2', value: 'value.value2'},
{id:'value.id3', name: 'value.name3', type: 'value.type3', value: 'value.value3'},
]
var result = {}
data.forEach(d => {
result[d.id] = d.value
})
console.log(result)
答案 1 :(得分:2)
您可以尝试一下
var data = [
{id:'value.id_1', name: 'value.name_1', type: 'value.type_1', value: 'value.value_1'},
{id:'value.id_2', name: 'value.name_2', type: 'value.type_2', value: 'value.value_2'},
{id:'value.id_3', name: 'value.name_3', type: 'value.type_3', value: 'value.value_3'},
]
let request = data.map(function(item){
let newItem = {};
newItem[item.id] = item.value;
return newItem;
})
console.log(request);
答案 2 :(得分:0)
您可以使用Array.reduce
根据最初拥有的对象数组来创建新对象。
我们在reduce的内部要做的就是将新的键/值分配给我们返回的对象。
var data = [
{id:'value.id', name: 'value.name', type: 'value.type', value: 'value.value'},
{id:'value.id2', name: 'value.name', type: 'value.type', value: 'value.value'},
{id:'value.id3', name: 'value.name', type: 'value.type', value: 'value.value'},
];
const ret = data.reduce((tmp, {
id,
value,
}) => (tmp[id] = value, tmp), {});
console.log(ret);
等同于:
var data = [
{id:'value.id', name: 'value.name', type: 'value.type', value: 'value.value'},
{id:'value.id2', name: 'value.name', type: 'value.type', value: 'value.value'},
{id:'value.id3', name: 'value.name', type: 'value.type', value: 'value.value'},
];
const ret = data.reduce((tmp, x) => (tmp[x.id] = x.value, tmp), {});
console.log(ret);