Reputation: 655
I searched online and read up on the Lodash documentation, but could not find a quick fix to this.
Basically, I have two arrays
var employee = ["John", "Mary"];
var location = ["APAC", "singapore"];
And eventually I would like to have a Json object that look like this:
var obj = {
"profile": [
{
"name": "John",
"location": ["APAC","Singapore"]
},
{
"name": "Mary",
"location": ["APAC","Singapore"]
}
]
}
Upvotes: 1
Views: 1149
Reputation: 82654
You could use _.zipWith with lodash:
var employee = ["John", "Mary"];
var location = ["APAC", "singapore"];
var output = {
profile: _.zipWith(employee, name => ({
name,
location
}))
};
console.log(output);
Upvotes: 3
Reputation: 1389
Here is a quick and dirty solution using map and node:
var obj = {
"profile": employees.map((name) => {
return {
"name": name,
"location": location
};
})
};
Upvotes: 0
Reputation: 92904
Don't use location
as variable name (var location ...
) because it will conflict with window.location object.
The solution using Array.prototype.reduce()
function:
var employee = ["John", "Mary"],
loc = ["APAC", "Singapore"],
result = employee.reduce(function (r, e) {
r.profile.push({"name": e, "location": loc.slice()});
return r;
}, {profile: []});
console.log(result);
Upvotes: 3
Reputation: 11
Maybe a simple loop will do the trick :
var obj = { "profile" : [] };
employee.forEach(function(e) {
obj.profile.push({ "name": e, "location": location });
});
Upvotes: 0
Reputation: 644
To achieve the above you could do the following using ES2015:
const employees = ["John", "Mary"];
const locations = ["APAC", "singapore"];
const final = []
employees.forEach( (employee) => {
let obj = {
name: employee,
location: [...locations]
}
final.push(obj)
})
Upvotes: 0