简体   繁体   中英

Javascript building an object directly

I have these values:

let buffer = {};
let value = 'value';
let x = 1;
let y = 2;

This is what I want to do:

buffer[x][y].value = value;

This is what I need to do, in order for it to work:

buffer[x] = {};
buffer[x][y] = {};
buffer[x][y].value = value;

My guess is that there is a better, maybe built in way to create an object like this in one step instead of three.

My guess is that there is a better, maybe built in way to create an object like this in one step instead of three.

What you have is fine, but you can also do it with computed properties (I'm assuming you need the values from variables) and shorthand property notation (for value ):

 let value = 'value'; let x = 1; let y = 2; let buffer = { [x]: { [y]: { value } } }; console.log(buffer); 

If you want to create nested object based on a set of keys, you could use reduceRight . Use the rest parameters syntax to get the value and the array of paths as separate variables. Set the value as the initialValue parameter and add a level of nesting in each iteration

 const create = (value, ...paths) => paths.reduceRight((r, k) => ({ [k]: r }), value) console.log(create("final value", "1", "2", "value")) console.log(create("final value", "any", "number", "of", "keys")) 

Like this?

const buffer = {
  1: {
    2: {
      value: 'value'
    }
  }
};

If x and y are already defined, then use computed properties:

 let x = 1; let y = 2; const buffer = { [x]: { [y]: { value: 'value' } } }; 

You could reduce the given keys and assign the value at the last step.

 const setValue = (object, path, value) => path.reduce((o, k, i, { length }) => o[k] = i + 1 === length ? value : o[k] || {}, object); let buffer = {}; let value = 'value'; let x = 1; let y = 2; setValue(buffer, [x, y, value], value); console.log(buffer); 

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