简体   繁体   中英

Add new value to an existing object with a variable content as the key?

I have an object 'unit', whose keys are different teams. Teams' keys are employees. Each employee is an object with its own fields. I'm looping through some files, getting each employee object. Once I get an employee object, I want to place into its proper team within the unit object. For example:

var indiv = {'Rich':{'a':3,'b':4,'c':5}};
var teamname = "TeamA";
var unit = {};
unit[teamname] = indiv;

//[object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... }
//   }
// }

Now, how can I add the following element to this object?

var indiv2 = {'Tom':{'a':6,'b':8,'c':10}};

So that the result is:

// [object Object] {
//   TeamA: [object Object] {
//     Rich: [object Object] { ... },
//     Tom: [object Object] { ... }
//   }
// }

Any clues? Is the only option turning TeamA into an array of objects?

Thanks!

One way of doing it is as below. With unit[teamname] = {}; you save an empty object under the key teamname . Then you add the single elements to this object under the keys Rich and Tom

 var rich = {'a':3,'b':4,'c':5} var tom = {'a':6,'b':8,'c':10} var name1 = "Rich" var name2 = "Tom" var unit = {}; var teamname = "TeamA"; unit[teamname] = {}; unit[teamname][name1] = rich; unit[teamname][name2] = tom; console.log(unit);

Assuming you have

const indiv = {'Rich':{'a':3,'b':4,'c':5}}
const indiv2 = {'Tom':{'a':6,'b':8,'c':10}}

You can use Object.assign

 const indiv = {'Rich':{'a':3,'b':4,'c':5}} const indiv2 = {'Tom':{'a':6,'b':8,'c':10}} const unit = { teamA: {} } Object.assign(unit.teamA, indiv) console.log(unit.teamA) Object.assign(unit.teamA, indiv2) console.log(unit.teamA)

If you don't want/can't change indiv , indiv2 structure, you can do it this way.

Get the key from indiv2 :

let key = Object.keys(indiv2)[0]

Get values:

let values = Object.values(indiv2)[0]

And now you can do it like this:

unit[teamname][key] = values

You want Object destructuring

 const both = {'Rich':{'a':3,'b':4,'c':5},'Tom':{'a':6,'b':8,'c':10}}; const teamName = "TeamA"; let unit = { [teamName] : {} }; unit[teamName] = {...both} console.log(unit);

One at a time:

 const persons = [ { 'Rich':{'a':3,'b':4,'c':5} }, { 'Tom':{'a':6,'b':8,'c':10} } ]; const teamName = "TeamA" let unit = { [teamName]: {} }; persons.forEach(person => unit[teamName] = { ...unit[teamName], ...person }) console.log(unit);

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