使用forEach遍历香草JS中的数组对象

时间:2018-07-27 19:57:14

标签: javascript

const users = {terry1: [{action: "unpaid", user: "terry1", member: true}, {action: "paid", user: "terry1", member: true}], malcomla3: [{action: "paid", user: "malcomla3", member: true}], jonny:[{action: "paid", user: "jonny", member: true}]}

我有类似上面的数据。每个键代表一个用户名,与之关联的数组是具有该用户相关字段的另一个对象,例如:{action: "paid", user: "doug101", member: true}

我正在尝试运行循环以遍历每个用户密钥,以查看它们是否对unpaid具有action的值,但我仍坚持如何继续下面的代码要做到这一点。

 for (var key in users) {
     users[key].forEach(x => {

     })

  }

4 个答案:

答案 0 :(得分:1)

要使用forEach完成您开始的代码,请按以下步骤操作,使用.hasOwnProperty()检查数组中的对象是否为action,是否为{它“未付款”。

注意,基于注释,我将用户对象数组之一添加了第三项。

堆栈片段

const users = {
  terry1:    [
               {action: "paid", user: "terry1", member: true},
               {action: "unpaid", user: "terry1", member: true},
               {action: "paid", user: "terry1", member: true}
             ],
  malcomla3: [
               {action: "paid", user: "malcomla3", member: true}
             ],
  jonny:     [
               {action: "paid", user: "jonny", member: true}
             ]
}


for (var key in users) {
  users[key].forEach( function(item) {
    for (var key2 in item) {
      if( item.hasOwnProperty("action") && item[key2] == "unpaid" ) {
         console.log(key, 'not paid')
      }
    }
  })
}

答案 1 :(得分:0)

如果要修改数组并获取数组中的所有unpaid对象,请遍历键并过滤具有操作为unpaid的对象

for (k in users) { users[k] = users[k].filter(function(obj) { return obj.action === 'unpaid';}) }

答案 2 :(得分:0)

您可以从对象中获取条目,搜索所需的键,然后使用该数组或将其重构为对象,如下所示:

const users = {
  terry: [{action: "paid"}, {cool: false}],
  alice: [{action: "unpaid"}]
};
const unpaid = Object.entries(users).filter(([name, fields]) => fields.find(field => field.action === "unpaid"));

const unpaid_as_object = Object.assign(...unpaid.map(([k,v]) => ({[k]: v})));
console.log(unpaid_as_object);

答案 3 :(得分:0)

如果您真的想使用forEach,那么此代码段应该可以使用

const users = {terry1: [{action: "unpaid", user: "terry1", member: true}, {action: "paid", user: "terry1", member: true}], malcomla3: [{action: "paid", user: "malcomla3", member: true}], jonny:[{action: "paid", user: "jonny", member: true}]};

for (var key in users) {
  users[key].forEach(user => {
    if (user.hasOwnProperty("action") && user.action === "unpaid") {
      console.log(user.user + " is unpaid")
    }
  })
}