Steps to allocate the asset in case of null value

I encountered a situation where I had an array of objects with duplicate ids. Each object linked to the id contains two properties: A and B. In the first index of the array, property A has a value while property B is null. Conversely, in the second index, property A is null and property B has a value. The goal is to merge these two indexes based on the same id. However, the output currently does not display values for both properties A and B - one of them remains null.

Array

{
  id: 123,
  A: “value A1”,
  B: null
},
{
  id: 123,
  A: null,
  B: “value b”
},
{
  id: 123,
  A: “value A2”,
  B: null
},
{
  id: 456,
  A: "a2 value",
  B: "b2 value"
}

Code

var output = _.groupBy(arr, function(o){
   return o.id;
})

Output

{
  id: 123,
  A: [“value A1”, “value A2”],
  B: null
},
{
  id: 456,
  A: ["a2 value"],
  B: "b2 value"
}

Expected

{
  id: 123,
  A: [“value A1”, “value A2”],
  B: “value b”
},
{
  id: 456,
  A: ["a2 value"],
  B: "b2 value"
}

Answer №1

Here is a way to achieve this without using underscore and loadash:

var items = [
    {
        id: 123,
        A: "value A1",
        B: null
    },
    {
        id: 123,
        A: null,
        B: "value b"
    },
    {
        id: 123,
        A: "value A2",
        B: null
    },
    {
        id: 456,
        A: "a2 value",
        B: "b2 value"
    }    
];

var updatedItems = items.reduce((accumulator, currentItem) => {
    var existingItem = accumulator.find(item => item.id === currentItem.id);
    if (existingItem) {
        currentItem.A && (existingItem.A.push(currentItem.A));
        existingItem.B = existingItem.B || currentItem.B;
    } else {
        currentItem.A = currentItem.A ? [currentItem.A] : [];
        accumulator.push(currentItem);
    }
    return accumulator;
}, []);

console.log(updatedItems);

Answer №2

Here's an example using plain JavaScript without the need for underscore or lodash.

var data = [{
    id: 123,
    A: "some value",
    B: null
  },
  {
    id: 123,
    A: null,
    B: "b value"
  },
  {
    id: 456,
    A: "a2 value",
    B: "b2 value"
  }
];

var outputObject = {},
  outputArray = [];

data.forEach(function(obj) {

  if (!outputObject[obj.id]) {
    outputObject[obj.id] = obj;
  } else {
    if (obj.B !== null) {
      outputObject[obj.id].B = obj.B;
    }
    if (obj.A !== null) {
      outputObject[obj.id].A = obj.A;
    }
  }

});

//Convert to an array
Object.keys(outputObject).forEach(function(key) {
  outputArray.push(outputObject[key]);
});

console.log(outputArray);

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

Safari encountering parsing date error

My Angular application is receiving date formats from a web service in the following format: myDate = "2020-03-05T08:00:00" This translates to the fifth of March, 2020 for me For Chrome, Firefox, and IE, the format is yyyy-mm-ddThh:mm:ss However, Safar ...

What might be causing the attribute of this Backbone model to be undefined when attempting to access it?

I have a straightforward REST API that provides information about an item at /api/items/:id, which includes the ID and name. I am using a Router to organize my Backbone views. The edit route creates a FormEditItem view, passing the ID from the URL. To ret ...

At what specific times is it most appropriate to use parentheses when dealing with functions?

Check out my code snippet below: const cleanRoom = function() { return new Promise(function(resolve, reject) { resolve('Cleaned The Room'); }); }; const removeGarbage = function(message) { return new Promise(function(resolve, reject) ...

Issues with jQuery tabs

I am looking to incorporate multiple tab constructions on my website. I have created an HTML page and a JavaScript page for these tabs. Here is the code I have implemented in the header: <script type="text/javascript"> $(document).ready(fu ...

Struggling to connect the Calendar data in AngularJS

I am a beginner in angular js and facing an issue with binding the value of the calendar date from the jquery calendar picker. It seems to be accepting the date only, while all other fields are getting bound correctly. Below is my HTML code: <input id ...

Custom shaped corrugated sheet in three dimensions

While constructing a house-like structure with corrugated sheets, I utilized BoxGeometry to outline the structure and adjusted vertices to create a corrugated sheet wall. I have been experimenting with creating a facade using corrugated sheets in the sh ...

Enhancing radar charts with tooltips in Chart.js

I've been trying to enhance the Radar chart in chart.js by adding tooltips, but so far I haven't had much success. Here are the three methods I attempted: 1st Method: var options = Chart.defaults.global = {showToolTips:true}; new Chart(ctx).Ra ...

What is the best way to combine a JSON response object with the variable J inside a for loop?

Received a JSON response as follows: { "name" : "chanchal", "login3" : "1534165718", "login7" : "1534168971", "login6" : "1534168506", "login5" : "1534166215", "login9" : "1534170027", "login2" : "1534148039", "lastname" : "khandelwal", ...

Exploring the interception of ajax http responses beyond the scope of AngularJS

Is there a way to capture and manage http responses from outside of Angular? $httpProvider is not an option since the target script loads after Angular has initialized. I need a solution that functions similar to ajaxSuccess in jQuery. ...

Is there a way for me to personally include pages in the browser's cache?

My webpage currently sends two requests: one to /login and another to /treeContents?rootID=9. I am interested in combining them into one request, specifically /loginAndTreeContents?rootID=9 The original method stores subsequent responses from /treeContent ...

Embracing the Quirks of JSON: A Call for a

Currently, I am in the process of developing a webpage that involves incorporating four distinct JSON entities (objects, arrays). Excuse my lack of appropriate jargon. Upon receiving the JSON data, it is structured as an object with numerous sub-objects, ...

The tags are showing unexpected strings after the v-for directive

Currently, I am in the process of designing a new web page using Vue on Nuxt to replace the existing one (using VScode). However, I have encountered an issue while utilizing v-for to generate lists. Within the tag, there is an unknown string(attribute) tha ...

An illustration of the fundamental concepts of require.js

main.md <markdown> <head> <script data-main="script" src="http://requirejs.org/docs/release/2.1.8/minified/require.js"></script> </head> <body></body> </markdown> script.css defi ...

What is the best way to save the user's response in an array for comparison with the correct answer?

Here's the concept behind how the quiz is designed to function: As the user enters their answer, it will be stored in an array for comparison with the correct answers stored in another array. var input = require("read_line-sync"); class Multiple_cho ...

Got lost after browsing and lost track of the reference window

I have successfully created a new browser window called win when the element with id #new-window-id is clicked. I have also set up an events system for that window, such as detecting if win.closed. Everything works fine until I navigate to links inside the ...

The error message "cordova is not defined" is indicating that the cordova.js file has already been loaded

While the app is running, I encountered the following: Uncaught ReferenceError: cordova is not defined ionic-core.js:466 Ionic Core: init ionic-core.js:145 Ionic Core: searching for cordova.js ionic-core.js:149 Ionic Core: cordova.js has already been load ...

The function of jQuery's .prop('defaultSelected') appears to be unreliable when used in Internet Explorer 9

Below is the code I am currently using: $selects = $('select'); $selects.val( $selects.prop('defaultSelected')); The purpose of this code is to reset the values of all select elements on my webpage. However, I am facing an issue in IE ...

Submitting a Form using AJAX in vanilla JavaScript (without the use of jQuery)

I'm looking for guidance on how to send a Form via an AJAX request. Specifically, I need help with the 'xmlhttp.open' line. The goal is to upload a video file to a third party video hosting site using their API and provided URL ('upload ...

By comparing two JSON arrays and using the matches found, create a third JSON array

In a specific scenario, I am required to compare two JSON arrays to check if their name fields match each other. If the name fields match, then I need to create a third JSON array. For example: Let's consider the first JSON array as [{"name":"hx ind ...

Using SVG Mask to enhance shape Fill

I am having trouble achieving the desired effect of darkening the fill of objects based on a specified gradient. Instead, when the mask is applied over the fill, it actually lightens it. I suspect that this issue arises from the color blending method being ...