我有这样的数据:
var data = {
value1: ["a", "b", "c"],
value2: [1, 2, 3]
}
Run Code Online (Sandbox Code Playgroud)
我想将其转换为:
var newData = [
{value1: "a", value2: 1},
{value1: "b", value2: 2},
{value1: "c", value2: 3}
]
Run Code Online (Sandbox Code Playgroud)
我怎样才能通过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);Run Code Online (Sandbox Code Playgroud)
更新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);Run Code Online (Sandbox Code Playgroud)
更新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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |