我有这样的数据:
var data = {
value1: ["a", "b", "c"],
value2: [1, 2, 3]
}
我想把它转换成:
var newData = [
{value1: "a", value2: 1},
{value1: "b", value2: 2},
{value1: "c", value2: 3}
]
如何使用 javascript 实现此目的?
最佳答案
使用Array#map
生成数组的方法。
var data = {
value1: ["a", "b", "c"],
value2: [1, 2, 3]
};
// iterate over the first property
var res = data.value1.map(function(v, i) {
// generate the array object element
return {
value1: v,
value2: data.value2[i]
}
});
console.log(res);
更新 1:如果属性名称未知,那么您可以执行类似的操作。
var data = {
value1: ["a", "b", "c"],
value2: [1, 2, 3]
};
// get all property names
var keys = Object.keys(data);
// iterate over the first property name array
var res = data[keys[0]].map(function(v, i) {
// generate the object by iterating over the keys array
return keys.reduce(function(obj, k) {
// define the object property
obj[k] = data[k][i];
// return the objet reference
return obj;
// set initial value as empty object
}, {});
});
console.log(res);
更新 2:如果数组长度可以不同,那么您需要从集合中获取更大的数组。
var data = {
value1: ["a", "b", "c", "d"],
value2: [1, 2, 3],
value3: [1, 2, 3, 5, 6, 7, 8]
};
// get all property names
var keys = Object.keys(data);
// iterate over the largest array
var res = data[
// get the largest array holding key from the keys array
keys.reduce(function(k, k1) {
return data[k1].length > data[k].length ? k1 : k;
})
].map(function(v, i) {
// generate the object by iterating over the keys array
return keys.reduce(function(obj, k) {
// check element exist in the array by comparing
// the length and index
if (data[k].length > i)
// define the property if value exist in index
obj[k] = data[k][i];
// return the objet reference
return obj;
// set initial value as empty object
}, {});
});
console.log(res);
关于javascript - 两个数组的对象到一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41500740/