【问题标题】:Filter and sort JSON formatted object?过滤和排序 JSON 格式的对象?
【发布时间】:2018-01-17 21:25:47
【问题描述】:

假设我有一个 JSON 格式的对象(如下所示),我想按 UserID 对其进行排序

oUserColors = { "users": [
    { "UserID": 31, "Color": "Red" },
    { "UserID": 30, "Color": "Red" },
    { "UserID": 32, "Color": "Green" },
    { "UserID": 30, "Color": "Green" },
    { "UserID": 32, "Color": "Red" }
 ] };

我可以很容易地使用以下函数来做到这一点。

objSortedUserColors = oUserColors.users.sort(function (a, b) {
        return b.UserID - a.UserID; // sort oUserColors.users in descending order.
 });

这会给我这个...

 objSortedUserColors = { "users": [
    { "UserID": 32, "Color": "Red" },
    { "UserID": 32, "Color": "Green" },
    { "UserID": 31, "Color": "Red" },
    { "UserID": 30, "Color": "Red" },
    { "UserID": 30, "Color": "Green" }
 ] };

但是,如果我还想按颜色过滤对象,如果用户同时使用红色和绿色作为颜色,那么红色会被移除,只剩下绿色。但是如果用户只有红色作为他们的颜色,它就会保持不变。导致这样的事情......

 objFilteredSortedUserColors = { "users": [
    { "UserID": 32, "Color": "Green" },
    { "UserID": 31, "Color": "Red" },
    { "UserID": 30, "Color": "Green" }
 ] };

我被困住了。任何建议将不胜感激!

【问题讨论】:

  • 请向我们展示您迄今为止尝试过的对您不起作用的方法。
  • 缺少最重要的标签javascript。其次,似乎排序与您的问题无关......为什么还要提到它?
  • "一个JSON格式的对象"---没有这个东西,它只是一个JS对象。
  • @trincot:好点。我原本以为我可以一次性排序/过滤。看来我应该先排序,然后过滤..

标签: javascript arrays json sorting


【解决方案1】:

您知道如何对数组进行排序,我将只关注过滤器。您可以为此使用reduce 和一个帮助对象来维护由UserUD 键入的值。 Map 也可以,但是当普通对象是非负整数时,普通对象具有按键递增的顺序生成值的优势。

const oUserColors = { "users": [{ "UserID": 31, "Color": "Red" },{ "UserID": 30, "Color": "Red" },{ "UserID": 32, "Color": "Green" },{ "UserID": 30, "Color": "Green" },{ "UserID": 32, "Color": "Red" }]};

const result = Object.values(oUserColors.users.reduce( (acc, obj) => {
    const prev = acc[obj.UserID];
    if (!prev || prev.Color === 'Red') {
        acc[obj.UserID] = obj;
    }
    return acc;
}, {}));

console.log(result);

这个想法是构建一个对象 (acc),它只包含感兴趣的值,由 UserID 键入。如果您发现在此收集期间还没有 UserID 的值,则添加它。如果有一个值,并且它的颜色为红色,那么用当前对象替换它是安全的。

使用Object.values(),您可以将该对象转换回数组。

由于所有常见浏览器中的 JavaScript 都会按数字键顺序(如果是非负整数)生成值,因此输出将被排序。

【讨论】:

  • 最有帮助,先生!非常感谢!
猜你喜欢
  • 2021-02-04
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多