javascript - filter unique properties from array of objects with unique values if existing then override the value -


i trying iterate array of objects different properties. adding objects dynamically , want check whether property of object exist in array override value else add array.

for e.x.

var arr = [             {"value":"abc"},             {"type":"def"},             {"status":"ghi"},             {"value":"xyz"}             ] 

expected result:

arr = [             {"value":"xyz"},             {"type":"def"},             {"status":"ghi"} 

]

what trying far not working. here code:

var arr = [             {"value":"abc"},             {"type":"def"},             {"status":"ghi"},             {"value":"abc"}             ]             var obj={};             var key1 = "type", value="xyz";             obj[key1] = value;             var newarr = arr.filter(function(entry,i) {                 if (!entry.hasownproperty(key1)) {                     return true;                 }             });             newarr.push(obj); 

please note, obj dynamic code working fine first time when property of key1 doesn't change. once change value of key1 "type" "status", adding objects 2 times.

can me around this?

try array.reduce() function , object.keys() method.

  1. array#reduce() used recreate new array
  2. object.keys() key of each object .array#map() create array of object keys .
  3. then match if not includes in array push new array

updated replace type new 1 value

var arr = [{"value":"abc"}, {"type":"def"}, {"status":"ghi"}, {"value":"xyz"}];      var key1 = "type";      var value="xyz";                   var  result = arr.reduce((a,b) =>{      if(!a.map(i=> object.keys(i)[0]).includes(object.keys(b)[0]))      {     if(b.hasownproperty(key1)){        b[key1]=value    }      a.push(b)      }      return a}, []);                  console.log(result);


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -