简体   繁体   English

法线贴图与减少

[英]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.虽然我在第一次尝试中成功了,但使用 reduce 却无法得到结果。 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.这是使用flatMap()Object.values的一种方法,然后展平结果。 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以这种方式使用 Object.values 作为参数是将 map 参数直接应用到 Object.values 方法并返回结果的简写

 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM