现有如下两组数据
var arr1 = [{ "a": 1, "b": 2, "c": 3 }];
var arr2 = [{ "d": 4, "f": 5 }];
怎么样能拼接成这样的
var arr3 = [
{"a": 1, "d": 4},
{"a": 1, "f": 5},
{"b": 2, "d": 4},
{"b": 2, "f": 5},
{"c": 3, "f": 5}
]
现有如下两组数据
var arr1 = [{ "a": 1, "b": 2, "c": 3 }];
var arr2 = [{ "d": 4, "f": 5 }];
怎么样能拼接成这样的
var arr3 = [
{"a": 1, "d": 4},
{"a": 1, "f": 5},
{"b": 2, "d": 4},
{"b": 2, "f": 5},
{"c": 3, "f": 5}
]
function merge(...args) {
const cartesian = function*(arr) {
if (!arr.length) {
yield {};
} else {
const [[obj], ...rest] = arr;
for (const key in obj) {
for (const item of cartesian(rest)) {
yield { [key]: obj[key], ...item };
}
}
}
};
const ret = [];
for (const obj of cartesian(args)) ret.push(obj);
return ret;
}
console.dir(merge(
[{ a: 1, b: 2, c: 3 }],
[{ d: 4, e: 5 }],
[{ f: 6 }]
));
如果期望是下面
//期望
var arr3 = [
{"a": 1, "d": 4},
{"a": 1, "f": 5},
{"b": 2, "d": 4},
{"b": 2, "f": 5},
{"c": 3, "f": 5},
{"c": 3, "d": 4}
]
方法可以是这样
function spcz(arr1,arr2) {
const obj1 = arr1[0];
const obj2 = arr2[0];
let arr3 = [];
for(item1 in obj1) {
for(item2 in obj2) {
arr3.push(Object.assign({[item1]:obj1[item1]},{[item2]:obj2[item2]}));
}
}
return arr3;
}
10 回答11.3k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.2k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答5.2k 阅读✓ 已解决
1 回答3.4k 阅读✓ 已解决
3 回答2.4k 阅读✓ 已解决
通过for in 双循环具体代码如下 .