Abel
Abel

Reputation: 1614

How to assign the property if null

I had an array of objects with duplicated ids. Each object associated with the id has a property A and property B. For each loop, first index array's property A has value, but property B is null. In second index array, property A null, property B has value. The first two index will merge according to the same id. The output doesn't produce values for both property A and property B, but either one still 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"
}

Upvotes: 1

Views: 88

Answers (2)

Faly
Faly

Reputation: 13346

You can do it without underscore and loadash:

var arr = [
    {
        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 arr2 = arr.reduce((m, o) => {
    var sameObj = m.find(it => it.id === o.id);
    if (sameObj) {
        o.A && (sameObj.A.push(o.A));
        sameObj.B = sameObj.B || o.B;
    } else {
        o.A = o.A ? [o.A] : [];
        m.push(o);
    }
    return m;
}, []);

console.log(arr2);

Upvotes: 1

Thusitha
Thusitha

Reputation: 3511

Following is without underscore or lodash. Just with vanilla JavaScript.

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);

Upvotes: 0

Related Questions