简体   繁体   中英

How to loop over nested objects and arrays Javascript?

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

}

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

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

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