1

Dynamically I'm getting several objects having the following structure.

obj1 = {
   prop: 'one',
   key: 'string',
   value: 2
}

obj2 = {
   prop: 'one',
   key: 'diffString',
   value: 3
 }

Also, I have an object which I want to turn into this using received objects.

mainObject = {
   prop: {
     key1: value,
     key2: value
   }
}

I'm trying to use this

mainObject[obj.prop][obj.key] = obj.value;

But it gives me an error because at this point mainObject is just an empty object and it doesn't have mainObject[obj.prop]

Any help will be much appreciated.

2
  • 10
    mainObject[obj.prop] = {} first then mainObject[obj.prop][obj.key] = obj.value; Commented Oct 1, 2018 at 9:48
  • Your desired output doesn't use any of the property values from your input objects. Is that what you want, just to take the property names from the input? (If you actually want to use the values, e.g., "diffString" and 3, please edit the question to show an output example reflecting that.) Commented Oct 1, 2018 at 9:51

2 Answers 2

2

The simplest way to achieve this is as follows:

// If no value for obj.prop exists, assign empty object
mainObject[obj.prop] = mainObject[obj.prop] || {}; 

// Assign value to obj.key of object at mainObject[obj.prop]
mainObject[obj.prop][obj.key] = obj.value;

This code is first ensuring that a valid value (object) exists at the key obj.prop on mainObject. If there is not valid object at key obj.prop, then a new empty object is assigned {}.

The mainObject[obj.prop][obj.key] = obj.value assignment can now be performed safely seeing that an object exists at mainObject[obj.prop].

Alternatively, if you want a more concise way of doing this you could consider the lodash library which offers the .set() method:

_.set(mainObject, obj.prop + '.' + obj.prop, obj.value);

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It did help!
1

all you can do is push your upcoming object into an array and by using reduce method you can simply achieve your desired output

let mainObject = [obj1, obj2].reduce((result, obj) => {
    result[obj.prop] = result[obj.prop] || {};
    result[obj.prop][obj.key] = obj.value;
    return result;
}, {});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.