I have an object which consists of keys and values as lists
myObj = { "key1": [{"value": 1, "date": "2020"}], [{"value": 2, "date": "2020"}],
"key2": [{"value": 3, "date": "2020"}], [{"value": 4, "date": "2020"}]
}
I need to get the value of "value" key in this nested objects and reassign it as an array to the key.
So my ideal result is
myObj = { "key1": [1,2],
"key2": [3,4]
}
What I did
So I tried to loop over the object
for (var [k, v] of Object.entries(myObj)) {
v.forEach(function convertJSON(arr) {
console.log(arr.value);
});
console.log(k, v);
}
It works,
1
2
"key1": [{"value": 1, "date": "2020"}], [{"value": 2, "date": "2020"}]
3
4
"key2": [{"value": 3, "date": "2020"}], [{"value": 4, "date": "2020"}]
but when I tried to reassign the value it gives me undefined
for (var [k, v] of Object.entries(myObj)) {
newValue = v.forEach(function convertJSON(arr) {
console.log(arr.value);
});
v = newValue;
console.log(k, v);
}
UPDATE - Add my data
so I think it should like this
myData = { "impressions": [{value: 559, end_time: "2020年08月31日T07:00:00+0000"}],
[{value: 519, end_time: "2020年09月01日T07:00:00+0000"}],
"reach": [{value: 334, end_time: "2020年08月31日T07:00:00+0000"}],
[{value: 398, end_time: "2020年09月01日T07:00:00+0000"}}
}
2 Answers 2
You could take a flat map of the nested objects.
const
object = { key1: [{ value: 1, date: "2020" }, { value: 2, date: "2020" }], key2: [{ value: 3, date: "2020" }, { value: 4, date: "2020" }] },
result = Object.fromEntries(Object
.entries(object)
.map(([k, v]) => [k, v.map(({ value }) => value)])
);
console.log(result);
1 Comment
You can use Array.prototype.reduce()
method to achieve your desired output. The syntax of array reduce array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
. First get all the keys using Object.keys()
method and then traverse it and map each item of that keyed object by using Array.prototype.map()
method.
const myObj = {
impressions: [
{ value: 559, end_time: '2020-08-31T07:00:00+0000' },
{ value: 519, end_time: '2020-09-01T07:00:00+0000' },
],
reach: [
{ value: 334, end_time: '2020-08-31T07:00:00+0000' },
{ value: 398, end_time: '2020-09-01T07:00:00+0000' },
],
};
const ret = Object.keys(myObj).reduce((prev, c) => {
const p = prev;
p[c] = myObj[c].map((x) => x.value);
return p;
}, {});
console.log(ret);
Comments
Explore related questions
See similar questions with these tags.