Home > OS >  Can destructuring an array be used to map properties of each elements?
Can destructuring an array be used to map properties of each elements?

Time:11-13

Suppose there is an array like this:

const a = [ {p:1}, {p:2}, {p:3} ];

Is it possible to destructure this array in order to obtain p = [1, 2, 3] ?

Because this does not work :

const [ ...{ p } ] = a;   // no error, same as const p = a.p;
// p = undefined;

Edit

In response to all the answers saying that I need to use Array.prototype.map, I am aware of this. I was simply wondering if there was a way to map during the destructuring process, and the answer is : no, I need to destructure the array itself, then use map as a separate step.

For example:

const data = {
   id: 123,
   name: 'John',
   attributes: [{ id:300, label:'attrA' }, { id:301, label:'attrB' }]
};

function format(data) {
  const { id, name, attributes } = data;
  const attr = attributes.map(({ label }) => label);
  return { id, name, attr };
}

console.log( format(data) };
// { id:123, name:'John', attr:['attrA', 'attrB'] }

I was simply wondering if there was a way, directly during destructuring, without using map (and, respectfully, without the bloated lodash library), to retrive all label properties into an array of strings.

CodePudding user response:

Honestly I think that what you are looking for doesn't exist, normally you would map the array to create a new array using values from properties. In this specific case it would be like this

const p = a.map(element => element.p)

Of course, there are some packages that have many utilities to help, like Lodash's map function with the 'property' iteratee

CodePudding user response:

you can destructure the first item like this :

const [{ p }] = a;

but for getting all values you need to use .map

and the simplest way might be this :

const val = a.map(({p}) => p)

CodePudding user response:

Here's a generalized solution that groups all properties into arrays, letting you destructure any property:

const group = (array) => array.reduce((acc,obj) => {
  for(let [key,val] of Object.entries(obj)){
    acc[key] ||= [];
    acc[key].push(val)
    }
    return acc
  }, {})

const ar = [ {p:1}, {p:2}, {p:3} ]; 
const {p} = group(ar)
console.log(p)

const ar2 = [{a:2,b:1},{a:5,b:4}, {c:1}]
const {a,b,c} = group(ar2)
console.log(a,b,c)

  • Related