我在网上搜索并阅读了Lodash文档,但找不到快速解决方法。
基本上,我有两个数组
var employee = ["John", "Mary"];
var location = ["APAC", "singapore"];
最后我想要一个看起来像这样的Json对象:
var obj = {
"profile": [
{
"name": "John",
"location": ["APAC","Singapore"]
},
{
"name": "Mary",
"location": ["APAC","Singapore"]
}
]
}
答案 0 :(得分:3)
请勿使用static_cast
作为变量名称(location
),因为它会与window.location对象冲突。
使用var location ...
函数的解决方案:
Array.prototype.reduce()

答案 1 :(得分:3)
您可以将_.zipWith与lodash:
一起使用var employee = ["John", "Mary"];
var location = ["APAC", "singapore"];
var output = {
profile: _.zipWith(employee, name => ({
name,
location
}))
};
console.log(output);
答案 2 :(得分:0)
要实现上述目标,您可以使用ES2015执行以下操作:
const employees = ["John", "Mary"];
const locations = ["APAC", "singapore"];
const final = []
employees.forEach( (employee) => {
let obj = {
name: employee,
location: [...locations]
}
final.push(obj)
})
答案 3 :(得分:0)
以下是使用地图和节点的快速而肮脏的解决方案:
var obj = {
"profile": employees.map((name) => {
return {
"name": name,
"location": location
};
})
};
答案 4 :(得分:0)
也许一个简单的循环可以解决这个问题:
var obj = { "profile" : [] };
employee.forEach(function(e) {
obj.profile.push({ "name": e, "location": location });
});