What is the best way to combine key-value pairs objects into a single object using JavaScript?

I am faced with the challenge of creating a new object that combines keys from a specific array (const props = []) and values from existing objects. If a key does not exist in an object, I aim to populate it with null or placeholder values.

Here is my current code:

const props = ["name", "price", "qty", "category"]
let len = props.length;

const obj_1 = {
  name: "Product_1",
  price: 120,
  category: 'phone'
}

const obj_2 = {
  name: "Product_2",
  price: 7893,
  category: 'program_eq',
  qty: 5
}

const final_obj = {
  name: ["Product_1", "Product_2"],
  price: [120, 7893],
  category: ["phone", "program_eq"],
  qty: [null, 5]
}

I have devoted significant time to finding a solution to this issue, and while I have a partial one, it only retrieves data from the first object. My approach involves using lodash/map to handle different types of collections.

You can find my tentative solution below:

const final_obj = {};
    const props = ["name", "price", "qty", "category"];
    let len = props.length;

    const obj = {
      c1s6c156a1cascascas: {
        item: {
          name: "Product_1",
          price: 120,
          category: "phone"
        }
      },
      c454asc5515as41cas78: {
        item: {
          name: "Product_2",
          price: 7893,
          category: "program_eq",
          qty: 5
        }
      }
    };

    _.map(obj, (element, key) => {
      console.log(element.item);
      while (len) {
        let temp = props.shift();
        let tempData = [];
        if (element.item.hasOwnProperty([temp])) {
          tempData.push(element.item[temp]);
        } else {
          tempData.push("---");
        }
        final_obj[temp] = tempData;
        len--;
      }
    });
    console.log(final_obj); 
    
    //
    category:["phone"]
    name:["Product_1"],
    price:[120],
    qty:["---"],

Answer №1

To achieve this task, you can utilize the reduce() method to return an object and then incorporate a forEach() loop within it.

const properties = ["name", "price", "qty", "category"];
const objectData = {"c1s6c156a1cascascas":{"item":{"name":"Product_1","price":120,"category":"phone"}},"c454asc5515as41cas78":{"item":{"name":"Product_2","price":7893,"category":"program_eq","qty":5}}}

const finalResult = Object.values(objectData).reduce((resultObject, element) => {
  properties.forEach(property => {
    if(!resultObject[property]) resultObject[property] = []
    resultObject[property].push(element.item[property] || null)
  })
  return resultObject;
}, {})

console.log(finalResult)

Answer №2

The approach I would take is as follows:

const result = { };
const properties = ["name", "price", "qty", "category"];
const data = {"c1s6c156a1cascascas":{"item":{"name":"Product_1","price":120,"category":"phone"}},"c454asc5515as41cas78":{"item":{"name":"Product_2","price":7893,"category":"program_eq","qty":5}}}

// initializing each property as an empty array in the object
properties.forEach(prop => {
    result[prop] = [];
});

// iterating over each property in the data object
_.forOwn(data, value => {
    properties.forEach(prop => {
        // storing values (or undefined when not available) in the respective property array
        result[prop].push(value.item[prop]);
    });
});
console.log(result);

Answer №3

To achieve the same result, you can utilize various lodash functions.

Convert the array of properties into an object where the keys correspond to the values of the properties and the values are extracted from the object. If a property is not present in the object, return null.

const getValueFromObject = (obj, key) => _.map(obj, _.partial(_.get, _, key, null));
const setValueInResult = (res, key) => _.set(res, key, getValueFromObject(obj, 'item.' + key));
const groupByProperties = (props, obj) => _.transform(props, setValueInResult, {});

const props = ["name", "price", "qty", "category"];
const obj = {
  "c1s6c156a1cascascas": {
    "item": {
      "name": "Product_1",
      "price": 120,
      "category": "phone"
    }
  },
  "c454asc5515as41cas78": {
    "item": {
      "name": "Product_2",
      "price": 7893,
      "category": "program_eq",
      "qty": 5
    }
  }
}

console.log(groupByProperties(props, obj));
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4824272c293b20087c66797f667d">[email protected]</a>/lodash.min.js"></script>

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

Wrap each object in a container and then insert its key and values into that container using jQuery

How can I wrap each item and then insert the object's indexes and values into each created wrapper? I've attempted to accomplish this using the following code: $.ajax({ url: "some url", type: "GET", success: function(data) { var data ...

Automatically populate a dropdown list based on the selection made in another dropdown menu

I'm populating a second textbox based on the input of the first textbox in auto.jsp. Now, I want to automatically populate a combo box as well. How can I achieve this? Specifically, I want to autofill the second combo box based on the selection made i ...

What is the best way to create a new variable depending on the status of a button being disabled or enabled

Imagine a scenario where a button toggles between being disabled when the condition is false (opacity: 0.3) and enabled when the condition is true (opacity: 1). Let's set aside the actual condition for now -- what if I want to determine when the butt ...

Obtaining Compiled HTML Output Using AngularJS

I'm running into an issue with obtaining the compiled html of a page in AngularJS. Below is the code snippet that demonstrates this problem: JavaScript: <script src="http://code.angularjs.org/1.2.0rc1/angular.min.js"></script> &l ...

"Encountering an issue with the parameter 'undefined' in the .find()

Recently, I've been facing some challenges while using the .find() method within a vuex getter. I initialized a store with a list under state (pages) // state.js const state = { pages: [{id:1, content:"Page 1"}, {id:2, content:"Page 2"}] }; In my ...

Looking for a solution to eliminate Parsing Error: Unexpected Token when developing with React? I've already implemented ESLint and Prettier

Currently, I am working on building a form in React with MUI. Below is the code snippet that I have been working with: const textFields = [ { label: 'Name', placeholder: 'Enter a company name', }, { label: 'Addres ...

Indicate the highest value on Amcharts by drawing a line

I am currently working on plotting a graph that involves a significant amount of data. I have around 96 plots per day, and users can fetch data for up to a maximum range of 62 days. To implement this, I am utilizing Amcharts, but I have encountered an issu ...

Mobile version experiencing issue with Navbar not collapsing

The dropdown navigation bar on the mobile version of my website is not functioning properly. Despite several attempts, I have been unable to figure out a way to make it work effectively. <!DOCTYPE html> <html lang="en"> <head> & ...

Using Elasticsearch's bulk feature to set unique identifiers(_id) for documents

Whenever I attempt to insert documents into elasticsearch with a set _id, I encounter the following error: The field [_id] is considered a metadata field and cannot be included within a document. It should be utilized in the index API request parameters in ...

Image carousel with interactive buttons

I've taken over management of my company's website, which was initially created by someone else at a cost of $24,000. We recently made some edits to the slideshow feature on the site, adding buttons that allow users to navigate to corresponding p ...

Trigger an animation function with JQuery once the first one has finished

I am attempting to create a step-by-step animation of a div in JQuery. Each animation is triggered by a click, followed by a double-click, and so on. My issue arises when the animations overlap. When I double-click the div, both the first and second anima ...

Is it possible to iterate over an array and invoke a function at the same time?

const students = ['John', 'Mark']; const weight = [92, 85] const height = [1.88, 1.76] function yourBodyMass(name, funct, mass, height) { console.log(`${name}, your body mass index is ${funct(mass, height)}.`) } function calculateBM ...

What would be the most optimal choice for sorting in this particular situation within my PHP script?

I have successfully written a PHP script that can extract specific movie titles and ratings from a large file. However, I now need to modify the script to sort the movie titles with 'XXX' at the bottom of the list. I've considered using usor ...

Utilizing Html.BeginCollectionItem helper to pass a collection with only a glimpse of the whole picture

After seeking guidance from Stephen Muecke on a small project, I have encountered an issue. The javascript successfully adds new fields from the Partial View and connects them to the model through "temp" values set by the controller method for the partial ...

What is the best way to eliminate an object from an array using JavaScript?

I am currently working with two arrays named totalArray and selectionArray. These arrays have dynamic values, but for the sake of example I have provided sample arrays below. My goal is to remove objects from totalArray based on their id rather than inde ...

Can you provide a way to directly calculate the total length of all arrays within an array of objects?

How can I find the total length of arrays in an array of objects based on a specific property? var myArray = [{ "a" : 1, "b" : another Array }, { "c" : 2, "b" : another Array } ..... ] Is there a more efficient way to achieve this instea ...

Loop through the JSON array and append every value to the list within AngularJS

I'm just starting to learn about Angular JS and I have a question. I receive a JSON array as an AJAX response from a PHP page. I want to iterate through this JSON array and push each value into a list like this: angular.forEach($scope.companies.area, ...

React app (storybook) experiencing loading issues with @font-face

I am struggling to load custom fonts from a local directory. Can someone provide assistance? Below is the code I am currently using: @font-face { font-family: 'My Custom Font'; src: url('./fonts/MyCustomFont.eot'); src: url(&apo ...

Creating automatic page additions using Node.js on Heroku?

Can you assist me with a challenge I'm facing? Currently, I am using node.js and heroku to deploy an application and each time I add a new post, I have to manually update my web.js file. This process was manageable when I had fewer pages, but now it&a ...

Select various items simultaneously by pressing Ctrl and access them via form submission

Currently, I have a form with a list of days displayed. When a user clicks on a day, jQuery is used to populate a hidden field with the selected value. This allows me to reference the value in the post array. I now want to enhance this functionality by en ...