0

I have some variables in a loop which are different each iteration.

With those variables I want to fill a new object with some sub objects like so:

newProduct[key][prop][val] = "value";

What I want is an object like

car{ //key
   color: { //prop
       door: "value" //val + value
   }
}

But my problem is that [val] is not an object from [prop] and that is what Node.JS is trying to do.

I have tried it some other brackets like [prop[val]] and [prop + "." + val], but that doesn't seems to work. How can I get this to work?

1
  • I think you need to show us what do you have and what do you want? Commented Nov 3, 2017 at 11:37

3 Answers 3

2

You could check every property and use a default object. Later assign the value

function setValue(object, path, value) {
    var last = path.pop();
    path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}

var newProduct = {};

setValue(newProduct, ['car', 'color', 'door'], 42);

console.log(newProduct);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

1

Try with Object assign like that:

// It should be every iteration values
var key = 'car';
var prop = 'color';
var val = 'door';
var value = 'value';

var newProduct = Object.assign({ [ key ] :{ [ prop ] : { [ val ] : value }} });
console.log(newProduct);

Comments

0

You need to create each object at each layer before you can use it. Here's a very simple example. You could refine it to make it more re-usable, obviously:

var newProduct = {};
if (!newProduct["car"]) newProduct["car"] = {};
if (!newProduct["car"]["color"]) newProduct["car"]["color"] = {};
newProduct["car"]["color"]["door"] = "value";
console.log(newProduct);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.