简体   繁体   中英

Add array values into one json object using javascript or Lodash

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"]
    }
   ]
}

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); 

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);

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)
})

Here is a quick and dirty solution using map and node:

var obj = {
  "profile": employees.map((name) => {
    return {
      "name": name,
      "location": location
    };
  })
};

Maybe a simple loop will do the trick :

var obj = { "profile" : [] };
employee.forEach(function(e) {
    obj.profile.push({ "name": e, "location": location });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM