【问题标题】:I'm reading in a JSON of nested JavaScript Objects - I want to 'sort' it so objects that have a field with a certain value go to the top我正在阅读嵌套 JavaScript 对象的 JSON - 我想对其进行“排序”,以便具有特定值的字段的对象位于顶部
【发布时间】:2019-12-28 00:57:30
【问题描述】:

我正在阅读具有 javascript 对象映射的 JSON。所以..例如:

    { 
        offers : {
               "1":{"id":"1", "category":"a", "offerType":"LS"}, 
               "2":{"id":"2", "category":"a", "offerType":"EX"}, 
               "3":{"id":"3", "category":"a", "offerType":"EX"}, 
               "4":{"id":"4", "category":"a", "offerType":"LS"} 

        }
    }

当我阅读此 JSON 时,我将其存储在本地存储中。我想“排序”,以便所有具有“LS”offerType 的报价都显示在本地存储中我的对象的顶部。

我想这样做的原因是,当我在我的网站上显示这些优惠时,将首先显示带有 offerType“LS”的优惠。 我这样做是 Angular :

            let offers = data.offers;
                if (offers != null) {
                    for (var index in offers) {
                        var offer = offers[index];

                        if ( offer != undefined) {
                            if (offer.offerType == 'LS'){ 
                                offersLS = [...offersLS, offer];
                            }

                        }
                    }
                    if (offersLS != null){
                        offersLS.forEach(offerLS => {
                           let key =  offerLS['id'];
                           listOffers = offers[key], listOffers;
                        });

                    }
                listOffers = listOffers, offers;
            }

listOffers 最终被保存为我的本地存储对象。我曾尝试这样做: listOffers = [...offersLS, ...offers] 但这显然将它作为数组保存在我的 localStorage 中,我需要它成为这些对象或对象对象的“映射”。 .不完全确定正确的术语是什么。

【问题讨论】:

    标签: json angular typescript javascript-objects key-value


    【解决方案1】:

    首先,您必须知道对对象进行排序可能是一个坏主意,它不是为此而设计的。考虑使用数组。

    不管怎样,解决方案很简单,就是对键进行排序,然后根据这个新的键顺序重做一个对象:

    const offers = {
        "1":{"id":"1", "category":"a", "offerType":"LS"},
        "2":{"id":"2", "category":"a", "offerType":"EX"},
        "3":{"id":"3", "category":"a", "offerType":"EX"},
        "4":{"id":"4", "category":"a", "offerType":"LS"}
    };
    
    let value1;
    
    const sortedOffers = Object.keys(offers)
        .sort((k1, k2) => {
    
            // your sort rules here
    
            value1 = offers[k1];
    
            return value1.offerType === 'LS' ? -1 : 1;
        })
        .reduce((o, k) => {
            o[k] = offers[k];
            return o;
        }, {});
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-09
      • 1970-01-01
      • 2022-11-23
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-21
      • 1970-01-01
      相关资源
      最近更新 更多