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.
array#reduce()used recreate new arrayobject.keys()key of each object .array#map()create array of object keys .- then match if not
includesin 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
Post a Comment