Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Deconstructing an array of objects

I have this object

const config = {
    js: {
        files: [
            {
                src: './js/app.js',
                name: 'script.js',
                dest: 'public_html/js/'
            },
            {
                src: './js/admin.js',
                name: 'script.js',
                dest: 'public_html/js/'
            }
        ]
    }
};

and I want to get this (getting all the sources):

sources = ['./js/app.js', './js/admin.js']

// or, at least
sources = [{'./js/app.js'}]

I know how to do it with a loop, but can I do it with ES6 deconstructing?

Something like:

{sources = [{src}]} = config.js;

OR

{[{src}] : sources} = config.js;
like image 285
Claudiu Avatar asked Mar 04 '17 17:03

Claudiu


People also ask

How do you destruct an array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

Can you Destructure an array?

Array DestructuringValues in arrays are destructured based on their index . The variable can be named anything you want, but the variable name associated with the index is how it is assigned. We can also assign values to variables that are already declared.

What does it mean to Destructure an array?

by Kevwe Ochuko. Destructuring in JavaScript is a simplified method of extracting multiple properties from an array by taking the structure and deconstructing it down into its own constituent parts through assignments by using a syntax that looks similar to array literals.


2 Answers

Destructuring is not meant for a case such as this. Simply using map() will easily get the job done.

const config = {
    js: {
        files: [
            {
                src: './js/app.js',
                name: 'script.js',
                dest: 'public_html/js/'
            },
            {
                src: './js/admin.js',
                name: 'script.js',
                dest: 'public_html/js/'
            }
        ]
    }
};

console.log(config.js.files.map(x => x.src));
like image 155
m_callens Avatar answered Nov 15 '22 20:11

m_callens


You could use destructuring with an iterator like Array#entries and a for ... of statement and a temporary variable index.

var config = { js: { files: [{ src: './js/app.js', name: 'script.js', dest: 'public_html/js/' }, { src: './js/admin.js', name: 'script.js', dest: 'public_html/js/' }] } },
    index,
    result = [];

for ({ 0: index, 1: { src: result[index] } } of config.js.files.entries());

console.log(result)
like image 42
Nina Scholz Avatar answered Nov 15 '22 21:11

Nina Scholz