简体   繁体   中英

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"
}

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) { oA && (sameObj.A.push(oA)); sameObj.B = sameObj.B || oB; } else { oA = oA ? [oA] : []; m.push(o); } return m; }, []); console.log(arr2);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM