Exploring the power of ES6: Breaking down an array filled with objects

So I have this object:

const settings = {
    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'd like to extract all the sources. Something like this:

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

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

I know how to achieve this with a loop, but can I use ES6 destructuring instead?

Maybe something along these lines:

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

OR even:

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

Answer №1

Utilizing the map() function is more suitable for this scenario rather than using destructuring.

const data = {
    movies: [
        {
            title: 'Inception',
            genre: 'Sci-Fi',
            releaseDate: '2010'
        },
        {
            title: 'The Dark Knight',
            genre: 'Action',
            releaseDate: '2008'
        }
    ]
};

console.log(data.movies.map(item => item.title));

Answer №2

To easily extract data using an iterator, consider implementing destructuring along with Array#entries and a for ... of statement. It involves utilizing a temporary variable named 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)

Answer №3

If you're dealing with an array like this, destructuring without a loop or map isn't feasible.

One way to go about it is by employing destructuring in a for-of loop to navigate through the files:

let sources = [];
for (let {src} of data.js.files) {
  sources.push(src);
}

Alternatively, you could opt for a more efficient method using array functions:

// utilizing map
let sources = data.js.files.map(file => file.src);

// or via reduce
let sources = data.js.files.reduce((result, file) => result.concat(file.src), []);

Answer №4

Implement the Array.map() method in JavaScript.

DEMO

const data = {
    users: [
            {
                name: 'Alice',
                age: 25
            },
            {
                name: 'Bob',
                age: 30
            }
        ]
};

var names = data.users.map(function(user) {
  return user.name;
});

console.log(names);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Perform an Ajax request to retrieve and update Django template with fresh JSON data

After hours of troubleshooting, I still can't seem to figure out the issue at hand. I'm eager for my Django template to dynamically load new JSON data onto the user's screen as they scroll towards the bottom. Essentially, I aim to have my D ...

How can multiple buttons be added to each row in Jquery datatables and how can events be applied to them?

I currently have one button, but I am in need of two buttons. These buttons will trigger MySql commands when clicked to retrieve data from the database. How can I set up an event handler for these buttons? $(document).ready(function () { var table= ...

JavaScript and the proper way to format the weekdays

Learning programming is new to me, so please bear with me. I am currently utilizing Informer, a reporting website that retrieves data from Datatel, a unidata database. My current task involves working on a computed column that only accepts Javascript and ...

Encountering difficulty extracting information from an XML document within the Parse Cloud utilizing the XMLReader in an Express application

My goal is to extract elements from an XML file that I have already stored on the Parse Cloud for my Express app. I began coding after finding a helpful resource on using XMLReader with XPath on cloud code, as well as a guide on Parse httpRequest for retri ...

Vue.js component communication issue causing rendering problems

When it comes to the Parent component, I have this snippet of code: <todo-item v-for="(todo, index) in todos" :key="todo.id" :todo="todo" :index="index"> </todo-item> This piece simply loops through the todos array, retrieves each todo obj ...

Adding nested arrays in MongoDB using Java can greatly improve the structure and organization of

I am facing a challenge with adding an array named "discountList" inside another array called "simulatedProducts" using Java to populate a MongoDB collection. Currently, they are being added separately, and I am struggling to find a solution to have the di ...

Tips for utilizing ng-repeat with a function that generates a fresh object?

My HTML code includes the following element: <button ng-click="console.log(key)" ng-repeat="(key, value) in getLocalStorageKeys() track by $index"> In my JavaScript file, I have the following function: $scope.getLocalStorageKeys = function(){ ...

I require the ability to generate a fresh JSON file using Node.js

I'm encountering a problem while working on creating a new JSON file. Each time I attempt to use the writeFile function, it throws an error stating that the directory does not exist. Below is the code snippet that I have experimented with: fs.writeFil ...

What is the best way to make the current year the default selection in my Select control within Reactive Forms?

Hey there! I managed to create a select element that displays the current year, 5 years from the past, and 3 years from the future. But now I need to figure out how to make the current year the default selection using Reactive Forms. Any ideas on how to ac ...

Security Vulnerability in Ajax Callback Breakpoints

Imagine I have the following code snippet (partially pseudocode) $.ajax({ url: "/api/user", success: function(resp) { var data = JSON(resp) if (data.user.is_admin) // do admin thing else // do somet ...

What is the best approach to iterate through multiple input fields while maintaining separate states for each one?

Utilizing Vuetify to create text fields and applying v-model to a textFieldState results in all text fields sharing the same state, causing input from one field to leak into others. How can I ensure that each field maintains its own state? <div v- ...

Tips for inserting values into an array in NodeJS

Hello there! I am currently in the process of learning Node and experimenting with some interesting things using JavaScript and Node.js. However, I have hit a roadblock while trying to combine separate "where" statements in Sequelize into one cohesive stat ...

Launching a Node.js script with pm2 and implementing a delay

Utilizing the amazing pm2 package to maintain the longevity of my node.js applications has been extremely helpful. However, I have encountered a problem that I am unsure how to resolve. One of my applications involves multiple scripts, a server, and sever ...

Utilize Javascript to Populate Form Fields Based on "Selected Name"

I am currently facing a challenge in using javascript to automatically populate a form, specifically when it comes to setting the value for the country field. <form action="/payment" method="post" novalidate=""> <div class="input_group"> ...

Is it possible to create a system in NextJS that utilizes either the path or the query parameter?

Due to historical reasons, there is a need to maintain a blog link structure that resembles /blog?article=id-of-article. However, the goal is to implement pre-rendering with NextJS and have the blog URL appear as /blog/id-of-article. What is the most effe ...

Utilizing React Native to seamlessly integrate one JavaScript function into another

I am trying to integrate one javascript module into another. I recently downloaded a demo of GiftedMessanger After downloading the GiftedMessanger demo code, I incorporated all its dependencies into my own React Native (ios) project and successfully insta ...

When the ajax.beginform is successful, no action is required

Hey there, I've been attempting to utilize ajax.beginform in my asp.Net MVC project to trigger an alert upon success. However, I've hit a roadblock as I can't seem to get it working and no error messages are appearing either. [HttpPost ...

When Protractor is utilized and a button is clicked triggering an http request, an error is encountered while awaiting synchronization with Protractor

describe("Expectation: Display a list of cars for adding", function() { var car_add_button = element(by.id('add_car')); car_add_btn.click() // Encounter an issue, unable to proceed // more validations to be included... }); When executing t ...

Learn how to perform a post request in node js without triggering a page redirect or refreshing the form, all without using the preventdefault method

Is it possible to prevent the page from refreshing after sending data through an HTML form hitting a specific endpoint? I'm unsure about the best solution as there is no prevent default in nodejs, and I don't want the same page to redirect or re ...

What is the best way to extract value from an innerHTML object?

Is there a way for me to retrieve a parameter from a JSON page? I have the ability to run code on that page. alert(document.body.innerHTML) When this code is executed, it displays: <pre style="word-wrap:break-word;white-space: pre-wrap;">{"token": ...