Reputation: 1068
I am trying to iterate array of objects with different properties. where I am adding objects dynamically and want to check whether the property of the object is exist in the array then only override the value else add it to the array.
For e.x.
var arr = [
{"value":"abc"},
{"type":"def"},
{"status":"ghi"},
{"value":"xyz"}
]
expected result:
arr = [
{"value":"xyz"},
{"type":"def"},
{"status":"ghi"}
]
What I am trying so far is not working. Here is my 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, the obj will be dynamic so my code is working fine for first time when the property of key1 doesn't change. once I change the value of key1 from "type" to "status", It is adding objects 2 times.
Can anybody help me around this?
Upvotes: 0
Views: 635
Reputation: 22500
Try this Array.reduce()
function and Object.keys()
method.
array#reduce()
used to recreate with new arrayObject.keys()
get the key of the each object .Array#map()
create the array of all object keys .includes
in the array then push with new arrayUpdated replace the type
with new one 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);
Upvotes: 3
Reputation: 386746
You could use a hash table and filter and update all found same key objects.
var array = [{ value: "abc" }, { type: "def" }, { status: "ghi" }, { value: "ddd" }],
key = "type",
value = "xyz",
update = false,
hash = Object.create(null),
temp = {};
temp[key] = value;
array.push(temp);
array = array.filter(function (o) {
var key = Object.keys(o)[0];
if (!hash[key]) {
hash[key] = o;
return true;
}
hash[key][key] = o[key];
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 92884
The solution using ES6 Array.prototype.reduce()
and Object.assign()
functions:
var arr = [{"value":"abc"}, {"type":"def"}, {"status":"ghi"}, {"value":"xyz"}],
obj = arr.reduce((r,o) => Object.assign(r,o), {}),
result = Object.keys(obj).map( (k) => { o = {}; o[k]=obj[k]; return o } );
console.log(result);
Upvotes: 0
Reputation: 4972
The following code should do the job:
var arr = [
{"value":"abc"},
{"type":"def"},
{"status":"ghi"},
{"value":"xyz"}
];
var obj = {};
for (i in arr) {
key = Object.keys(arr[i])[0];
obj[key] = arr[i][key];
}
console.log(obj);
Upvotes: 0