【问题标题】:Manipulating array of object data in javascript在javascript中操作对象数据数组
【发布时间】:2018-10-28 09:35:25
【问题描述】:

所以我有一组数据,比如说......

    {'action': 'tweet', 'user': 'loser', 'message': 'fooboo'}
    {'action': 'follow', 'user': 'loser', 'message': null }
    {'action': 'tweet', 'user': 'loser', 'message': 'hello'}
    {'action': 'retweet', 'user': 'loser', 'message': null}
    {'action': 'tweet', 'user': 'michael', 'message': 'CIA is watching'}
    {'action': 'tweet', 'user': 'michael', 'message': 'HEHEHEHE'}
    {'action': 'follow', 'user': 'michael', 'message': null }

我正在尝试使用 reduce 遍历它并返回一个用户列表,其中包含他们所有操作的计数,例如

    { loser: 
            {
              tweets: 2
              retweets: 1
              follows: 1
            }
    }, michael:
            {
               tweets: 2
               retweets: 0
               follows: 1
            }
     }

这是我的代码...

    let userCount = tweets.reduce(function(users, line, idx) {
       users[line['users']] = users[line['user']] || [];
       let action = line['action];

       users[line.user].push({
         action: users[line.user].action + 1 || 0
       })
      return users
    }, {users: []});

我的代码没有成功计算或将动作的名称作为键注入对象。这就是我的输出数据的样子。

    { michael: [ { action: 1 } ],
      loser: [ { action: 1 }, { action: 1 }, { action: 1 } ],
    }

【问题讨论】:

  • 您是要我们为您编写代码吗?您尝试了哪些方法,哪些方法不起作用?
  • 用我拥有的当前代码编辑。对不起。我希望有一种更简单的方法来复制和粘贴代码,而不必每次缩进 8 个空格。
  • 你还没说什么不行?
  • 我只是对如何以这种方式成功地使用 reduce 操作对象感到困惑。每个在线资源都有一个非常基本的示例,例如 [2, 4, 4, 2, 1, 4, 5] 并返回每个数字的计数。我的稍微先进一点。我找不到类似格式的好例子。

标签: javascript arrays node.js object reduce


【解决方案1】:

您发布的代码存在几个问题,最明显的是,考虑到您想要的输出,您在对象和数组之间感到困惑(我假设)。

以下实现了您的要求,我已经用 cmets 对其进行了注释以概述正在发生的事情。

var tweets = [
  {action: 'tweet', user: 'loser', message: 'fooboo'},
  {action: 'follow', user: 'loser', message: null },
  {action: 'tweet', user: 'loser', message: 'hello'},
  {action: 'retweet', user: 'loser', message: null},
  {action: 'tweet', user: 'michael', message: 'CIA is watching'},
  {action: 'tweet', user: 'michael', message: 'HEHEHEHE'},
  {action: 'follow', user: 'michael', message: null },
];

const users = tweets.reduce((users, tweet) => {
  // Deconstruct tweet to get user and action
  const {user, action} = tweet;
  
  // Add user to users list, if they don't already exist
  if (users[user] === undefined) users[user] = {};
  
  // Increment user action count
  users[user][action] = (users[user][action] || 0) + 1;
                            
  return users;
}, {});

console.log(users);

【讨论】:

  • 谢谢。这就是我要找的。非常优雅干净。
  • 是的,我愿意。这很简单。使用 ES6 解构后,它非常易于阅读。感谢 cmets 的解释。
  • 如果您还可以解释为什么如果我将 reduce 输出更改为最后的数组,它的长度为 0,那就太好了。有没有办法确保reduce中的每次迭代都返回一个对象,所以我有一个对象数组?
  • JavaScript 中的数组只能有数字键,因此当您添加字符串键时,您是在向数组对象添加属性,而不是向数组本身添加项。因此,您需要更改数据的结构。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多