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;
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.
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.
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.
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));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With