简体   繁体   中英

Descontruct array of objects to get nested values ES6

I have an array of objects like:

const array = [
{
  name: 'object1', 
  value: true, 
  parameters: [
   { name: 'inner1', value: true},
   { name: 'inner2', value: false},
 ]
},
{
  name: 'object2', 
  value: false,
}

];

I need to get value of each object in array. To get object1 and object2 values I have used

const [{value: object1}, {value: object2}] = array;

How can I get values of objects which are in parameters array? How to deconstruct it in right way? Cannot find the right way..

You'd have to use parameters: and keep destructuring:

 const array = [{ name: 'object1', value: true, parameters: [{ name: 'inner1', value: true }, { name: 'inner2', value: false }, ] }, { name: 'object2', value: false, } ]; const [{ parameters: [ { value: value1 }, { value: value2 } ]}] = array; console.log(value1, value2); 

But that's not remotely readable IMO. I'd prefer to use standard dot/bracket notation to get to the parameters array, and .map to extract the values:

 const array = [{ name: 'object1', value: true, parameters: [{ name: 'inner1', value: true }, { name: 'inner2', value: false }, ] }, { name: 'object2', value: false, } ]; const values = array[0].parameters.map(({ value }) => value); console.log(values); 

You could take Array#flatMap and map the values of paramters only.

 const array = [{ name: 'object1', value: true, parameters: [{ name: 'inner1', value: true }, { name: 'inner2', value: false }] }, { name: 'object2', value: false }], values = array.flatMap(({ parameters = []}) => parameters.map(({ value }) => value)); console.log(values); 

The deconstruction must follow the shape of the object it is deconstructing. A good way to think of it in situations like this, is to just copy the object itself, and then replace each value with a variable name to assign that value to

// Object from which to deconstruct values
const myArray = [{
    name: 'object1', 
    value: true, 
    parameters: [
       { name: 'inner1', value: true},
       { name: 'inner2', value: false}]
    }];

// Deconstruction
const [{
    name: nameVar, 
    value: valueVar, 
    parameters: [
        { name: paramNameVar1, value: valueVar1},
        { name: paramNameVar2, value: valueVar2}]

     }] = myArray

Of course once you start getting more complex objects, it is possably more effort, less readable, and less efficient to deconstruct this way.

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