A guide on combining objects into an array using loops in JavaScript

I am facing an issue with transforming an array in JavaScript into a new object. Here is the initial array:

data = [
    {
        item: "Banana",
        path: "fruit"
    },
    {
        message: "Volvo",
        path: "car"
    },
    {
        message: "Cat",
        path: "animal"
    }
]

The desired output is to create a new object like this:

data = {
    fruit: "Banana",
    car: "Volvo",
    animal: "Cat"
}

I attempted to achieve this using a loop, but ran into some issues. Here is the code snippet:

var newData = [];

data.map(value => {
    newData[value.path] = value.message
});

However, the result I'm getting is structured differently. The loop returns an array instead of the desired object:

data = [
    {
        fruit: "Banana"
    },
    {
        car: "Volvo"
    },
    {
        animal: "Cat"
    }
]

Could you please provide guidance on how to solve this issue? Thank you.

Answer №1

To optimize your code, consider using the .reduce method:

const data = [
  {
    item: 'Banana',
    path: 'fruit'
  },
  {
    message: 'Volvo',
    path: 'car'
  },
  {
    message: 'Cat',
    path: 'animal'
  }
]

const res = data.reduce((acc, el) => ({ ...acc, [el.path]: el.message || el.item }), {})

console.log(res)

Alternatively, you can modify your existing solution by changing the array notation [] to object notation {}:

const data = [
  {
    item: 'Banana',
    path: 'fruit'
  },
  {
    message: 'Volvo',
    path: 'car'
  },
  {
    message: 'Cat',
    path: 'animal'
  }

var newData = {}

data.map(value => {
  newData[value.path] = value.message || value.item
})

console.log(newData)

Answer №2

Consider using the Array.prototype.reduce method instead of Array.prototype.map in your code:

const items = [{ name: "Apple", category: "fruit" }, { name: "Toyota", category: "car"}, { name: "Dog", category: "animal" }];

const combine = (items) => {
  return items.reduce((acc, item) => {
    acc[item.category] = item.name;
    return acc;
  }, {});
}
console.log(combine(items));

Answer №3

You have the option to construct an object using the given entries.

const
    info = [{ item: "Apple", type: "fruit" }, { message: "Toyota", type: "car" }, { message: "Dog", type: "animal" }],
    newObj = Object.fromEntries(info.map(({ item, message, type }) =>
        [type, item || message]
    ));

console.log(newObj);

Answer №4

When working within the .map callback function, make sure to create a brand new object instead of just assigning values. In this case, the key of the new object should be the same as the value of the path key in the original object, and the corresponding value should be the first non-path key's value:

const information = [
    {
        item: "Apple",
        path: "fruit"
    },
    {
        message: "BMW",
        path: "car"
    },
    {
        note: "Dog",
        path: "animal"
    }
];

const updatedData = information.map(({ path, ...others }) => ({
  [path]: Object.values(others)[0]
}));
console.log(updatedData);

Answer №5

Your approach is nearly flawless! Using square brackets notation for these cases is a smart move on your part.

To achieve the desired outcome, consider populating the properties of an empty object instead of mapping the values. Here's how you can do it:

var updatedData = {};

originalData.forEach(item => {
    updatedData[item.name] = item.value;
});

This change is necessary because the expected result should be an object (var updatedData = {}) rather than an array (var updatedData = []).

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

What is the method for retrieving a child element using its ID in JavaScript?

Below is the HTML code I am working with: <div id="note"> <textarea id="textid" class="textclass">Text</textarea> </div> I am trying to retrieve the textarea element without using document.getElementById("textid"). This is what I ...

Central alignment of div with cursor

I'm experimenting with creating a unique custom cursor using a <div> that trails the movement of the mouse pointer. While the current setup works smoothly, I've noticed that when scrolling down the page, the div lags behind until the scrol ...

Toggle the status of active to inactive instantaneously with the click of a

Incorporating DataTables with ajax using PHP CodeIgniter Framework has presented me with a challenge. I am struggling to toggle between Active and Inactive buttons seamlessly. My desired outcome: When the Active button is clicked, it should transition ...

How to Build Folders with NPM's fs-extra Module

I'm in need of some assistance. My goal is to construct a directory layout that resembles the following: parent child1 folder1 folder2 child2 folder1 folder2 Currently, I am utilizing the fs-extra npm module. The challenge I am ...

Python does not display values while using the second for loop

I tried to implement random selection in my dataset, but I encountered a challenge when attempting to nest all the data into an array using a for-loop. Dataset data = [ {"Item1": "Book", "Item2": "Pen", "It ...

Discovering how to locate a div element in one component from a separate component using Vue.js

Imagine having multiple Vue.js components in one project. <loginFields></loginFields> <submitButton></submitButton> Now, when the submitButton (which is a div with a unique id) is clicked, I want to initiate a method that checks t ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

What are the steps for utilizing Magento to generate an onclick event that sets parameters in a grid

Here is the current php code snippet I am working with: $this->addColumn('action_urls', array( 'header' => $this->__('Update LP'), //'index' => 'action_url', ...

The Vue.js component appears to be hidden within the Swal.fire HTML

Here is how I use Swal.Fire in my file1.js: import TextModuleComponent from "../components/TextModuleComponent"; export default { components: {TextModuleComponent} } Swal.fire({ title: 'Sending the offer via email?', ...

Removing the final element within a nested array: a step-by-step guide

let originalArray=[ [ "Test1", "4", "160496" ], [ "Test2", "6", "38355" ], [ "Test3", "1", "1221781" ], [ " ...

Retrieving text that has been HTML-escaped from a textarea using jQuery

Within my HTML file, I have a <textarea id="mytextarea"></textarea>. Suppose a user inputs the following text: <hello>, world! How can I retrieve res = "&lt;hello&gt;, world!"; based on the user's input? The current code s ...

jQuery smooth scrolling problem causing a one-second page "blinking" issue

Currently, I have implemented a smooth scrolling effect on my website using the following jQuery code: jQuery('html,body').animate({scrollTop:scrollTarget}, 1000, "swing"); Although the effect works well in general, I have noticed that when mul ...

Is it illegal to escape quotes when using an image source attribute and onerror event in HTML: `<img src="x" onerror="alert("hello")" />`?

Experimenting with escape characters has been a fascinating experience for me. <img src="x" onerror=alert('hello'); /> <img src="x" onerror="alert(\"hello\")" /> The second code snippet triggers an illegal character error ...

Enzyme fails to locate text within a div even though it is present

In my current test scenario, I have a set of data displayed in Material-UI Cards. The data is provided through a JSON array consisting of objects with fields like projectName, crc, dateCreated, createdBy, and lastModified. { projectName: 'P ...

The error message "SharedArrayBuffer is not defined" occurred when attempting to utilize ffmpeg.wasm

<!DOCTYPE html> <html> <head> <title>TikTok Live Downloader</title> </head> <body> <h1>TikTok Live Downloader</h1> <label for="username">Username:</label> ...

Implementing dynamic checkboxes in a design based on the length of a JSON array

I am looking to incorporate a dynamic checkbox within a linear layout that adjusts its size based on the JSON array retrieved from an API. The response from my API looks like this: [ { "id": 1, "alertName": "Device" }, { "id": 2, "alertName": "Email" } ] ...

Encountering the issue "Error: _LoginPage.default is not a constructor"

This is the code I wrote: /// \<reference types = "cypress" /\> class LoginPage { visit() { cy.visit("https://ec2-35-179-99-242.eu-west-2.compute.amazonaws.com:2021/") } username(name) ...

What is the best way to run tests on this asynchronous function using Jasmine?

My role in the service is listo: function () { var promiseResolved = $q.defer(); setTimeout(function () { promiseResolved.resolve(true); }, 2000); return promiseResolved.promise; } During my testing ...

Printing a modified div element that was created using jQuery on an ASP.NET MVC webpage after the initial page has finished loading

In my view, there is a div that holds multiple tables generated based on the model. Each row in these tables contains fields that can be edited using TextBoxFor. Through jQuery, rows can be moved between tables and new tables can be created dynamically wit ...

Learn how to handle JSON requests in Node.js within a router script

Hello everyone, I've been struggling to retrieve the body of a request from Postman into my scripts. The body always comes up empty. Can anyone help me figure out the correct way to do this? I have set up the server in index.js and reading the reques ...