existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}
我想将此javascript转换为其中没有数组项的内容,如下面的
desiredJsObj = [{"a":1, "b":11},{"a":2,"b":22},{"a":3, "b":33},{"a":4, "b":44}]
答案 0 :(得分:1)
我会这样做:
const income = {"a": [1,2,3,4], "b":[11,22,33,44]};
const res = income.a.map((a, i) => ({ a: a, b: income.b[i] }));
这假设“a”长度等于“b”长度。
答案 1 :(得分:1)
您可以在为结果使用新数组和对象时迭代键和值。
var object = { a: [1, 2, 3, 4], b: [11, 22, 33, 44] },
array = Object.keys(object).reduce(function (r, k) {
object[k].forEach(function (v, i) {
(r[i] = r[i] || {})[k] = v;
});
return r;
}, []);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
试试这个
existingJsObj = {"a": [1,2,3,4], "b":[11,22,33,44]}
desiredJsObj = []
keys = Object.keys(existingJsObj);
existingJsObj[keys[0]].forEach((val, index) => {
value = {};
keys.forEach((key, i) => value[key] = existingJsObj[key][index])
desiredJsObj.push(value)
})