简体   繁体   中英

Normal Mapping vs Reduce

I'm trying to convert an object into single array with just key and value. I tried two different ways. Though I succeeded in my first attempt but using reduce I am unable to get the result. Please kindly let me know if there is/are better ways of achieving the same. Thank you.

  var demoArr = [
            {
                "results": [
                {
                    "listing_id": 10544193
                },
                {
                    "listing_id": 4535435
                }
                ],
                "results1": [
                    {
                        "listing_id": 1054419363
                    },
                    {
                        "listing_id": 432535435
                    }
                ]
            }
        ];
        let aaa = [];
//          demoArr.map(x => {         (before)
            demoArr.forEach(x => {   //(after)
            let ss = Object.values(x);
//          ss.map(y => {              (before) 
            ss.forEach(y => {        //(after)
                y.forEach(k => {
                    aaa.push({"listing_id" : k.listing_id});
                })
               
            });
         });

Resulted in the following.

[{"listing_id":10544193},{"listing_id":4535435},{"listing_id":1054419363},{"listing_id":432535435}]

Is there a better way to achieve the above? Maybe by using reduce? I tried but failed to get the result.

         var ds = demoArr.reduce((a,value) => {
            a[value.listing_id] = a[value.listing_id] ? a[value.listing_id] : value
            return a
         },{});

Here's one way use flatMap() and Object.values , then flatten the result. Using Object.values as an argument in this fashion is a shorthand for applying the map argument directly into the Object.values method and returning the result

 var demoArr = [{ "results": [{ "listing_id": 10544193 }, { "listing_id": 4535435 } ], "results1": [{ "listing_id": 1054419363 }, { "listing_id": 432535435 } ] }]; let output = demoArr.flatMap(Object.values).flat(); console.log(output)

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