【问题标题】:How to create an array from an array of objects如何从对象数组创建数组
【发布时间】:2016-09-20 16:45:53
【问题描述】:

鉴于以下情况:

var example = [{
  "logged": {
    "status": 0,
    "status_name": "Logged",
    "hours": 23 // to the hours array
  },
  "pending": {
    "status": 3,
    "status_name": "Pending",
    "contribution": {
      "hours": 0,
      "count": 0
    },
    "verification": {
      "hours": 6, // to the hours array
      "count": 1
    }
  },
  "denied": {
    "status": 4,
    "status_name": "Denied",
    "contribution": {
      "hours": 0,
      "count": 0
    },
    "verification": {
      "hours": 0, // to the hours array
      "count": 0
    }
  },
  "approved": {
    "status": 2,
    "status_name": "Approved",
    "contribution": {
      "hours": 4.5,
      "count": 1
    },
    "verification": {
      "hours": 0, // to the hours array
      "count": 0
    }
  }
}];

我将如何构造两 (2) 个这样的数组:

var statusNames = ["Logged", "Pending", "Denied", "Approved"];
var hours = [23, 6, 0, 0];

如果解决方案中的值,我可以推断出如何获得其余部分。

【问题讨论】:

  • 数组中有更多条目还是只有1个?
  • 那么,你想要一个包含所有键的数组,另一个包含特定键的所有值的数组——一个可以任意嵌套的数组——对吗?
  • 我猜这不是简单的方法,您需要遍历每个元素并将其添加到数组中
  • 只是Array#map 的一个常规用例...您付出了哪些努力?
  • @PritamBanerjee 我认为这并不难。在我看来,第一个任务是微不足道的,第二个任务很简单。已经有内置方法可以在数组中进行交互以产生这些结果。

标签: javascript arrays arraylist


【解决方案1】:

您可以遍历数组和键,检查属性是否存在并将想要的部分包含到数组中。

var example = [{ "logged": { "status": 0, "status_name": "Logged", "hours": 23 }, "pending": { "status": 3, "status_name": "Pending", "contribution": { "hours": 0, "count": 0 }, "verification": { "hours": 6, "count": 1 } }, "denied": { "status": 4, "status_name": "Denied", "contribution": { "hours": 0, "count": 0 }, "verification": { "hours": 0, "count": 0 } }, "approved": { "status": 2, "status_name": "Approved", "contribution": { "hours": 4.5, "count": 1 }, "verification": { "hours": 0, "count": 0 } } }],
    statusNames = [],
    hours = [];

example.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        if ('hours' in o[k]) {
            statusNames.push(k);
            hours.push(o[k].hours);
            return;
        }
        if ('verification' in o[k]) {
            statusNames.push(k);
            hours.push(o[k].verification.hours);
        }
    });
});
console.log(statusNames);
console.log(hours);

【讨论】:

    【解决方案2】:

    使用Object.keys方法获取所有对象属性名数组,然后使用Array#map方法生成结果数组。

    // array for storing the hours value
    var hours = [];
    // genarte the statusName array
    var statusNames = Object.keys(example[0]) // get object keys
                // iterate over key value          
                .map(function(k) {
                    // get the value of hour and push it to hours array
                    // get `hours` property if defined or get hours property
                    // of nested object verification or push 0
                    hours.push(example[0][k].hours || example[0][k].verification.hours || 0); 
                    // get the status name and return
                    return example[0][k].status_name;
                })
    

    var example = [{
      "logged": {
        "status": 0,
        "status_name": "Logged",
        "hours": 23 // to the hours array
      },
      "pending": {
        "status": 3,
        "status_name": "Pending",
        "contribution": {
          "hours": 0,
          "count": 0
        },
        "verification": {
          "hours": 6, // to the hours array
          "count": 1
        }
      },
      "denied": {
        "status": 4,
        "status_name": "Denied",
        "contribution": {
          "hours": 0,
          "count": 0
        },
        "verification": {
          "hours": 0, // to the hours array
          "count": 0
        }
      },
      "approved": {
        "status": 2,
        "status_name": "Approved",
        "contribution": {
          "hours": 4.5,
          "count": 1
        },
        "verification": {
          "hours": 0, // to the hours array
          "count": 0
        }
      }
    }];
    
    var hours = [];
    var statusNames = Object.keys(example[0]).map(function(k) {
      hours.push(example[0][k].hours || example[0][k].verification.hours || 0);
      return example[0][k].status_name;
    })
    
    console.log(hours, statusNames)

    【讨论】:

      【解决方案3】:

      你必须使用 Array.prototype.reduce 来过滤你需要的信息。

      var example = [{
        "logged": {
          "status": 0,
          "status_name": "Logged",
          "hours": 23 // to the hours array
        },
        "pending": {
          "status": 3,
          "status_name": "Pending",
          "contribution": {
            "hours": 0,
            "count": 0
          },
          "verification": {
            "hours": 6, // to the hours array
            "count": 1
          }
        },
        "denied": {
          "status": 4,
          "status_name": "Denied",
          "contribution": {
            "hours": 0,
            "count": 0
          },
          "verification": {
            "hours": 0, // to the hours array
            "count": 0
          }
        },
        "approved": {
          "status": 2,
          "status_name": "Approved",
          "contribution": {
            "hours": 4.5,
            "count": 1
          },
          "verification": {
            "hours": 0, // to the hours array
            "count": 0
          }
        }
      }]
      
      var statusNames = example.reduce(function(prevVal, currVal) {
        for(var key in currVal) {
          if(!Object.prototype.hasOwnProperty.call(currVal, key)) continue
      
          if(currVal[key].status_name) {
            prevVal.push(currVal[key].status_name)
          }
         
        }
        return prevVal
      }, [])
      
      
      console.log(statusNames)

      【讨论】:

        【解决方案4】:

        这应该可行。

        // get all of the objects keys
        var statusNames = Object.keys(example);
        var hours = [];
        
        // get all of the hours
        example.forEach( function(item, idx){
            idx === 0 ? hours.push(item.hours) : false; // because the hours in your first object is not nested.
            idx > 0 ? hours.push(item.verification.hours) : false; // gets all of the nested hours.
        });
        

        【讨论】:

          【解决方案5】:

          使用for (var key in example[0]) 迭代每个键。

          然后将值压入各自的数组中

          statusNames.push(key); hours.push(example[0][key]["hours"] || example[0][key]["verification"]["hours"] );

          var  statusNames = [];
             var hours = [];
             
          var example = [{
            "logged": {
              "status": 0,
              "status_name": "Logged",
              "hours": 23 // to the hours array
            },
            "pending": {
              "status": 3,
              "status_name": "Pending",
              "contribution": {
                "hours": 0,
                "count": 0
              },
              "verification": {
                "hours": 6, // to the hours array
                "count": 1
              }
            },
            "denied": {
              "status": 4,
              "status_name": "Denied",
              "contribution": {
                "hours": 0,
                "count": 0
              },
              "verification": {
                "hours": 0, // to the hours array
                "count": 0
              }
            },
            "approved": {
              "status": 2,
              "status_name": "Approved",
              "contribution": {
                "hours": 4.5,
                "count": 1
              },
              "verification": {
                "hours": 0, // to the hours array
                "count": 0
              }
            }
          }];
          
          
          for (var key in example[0]) {
                statusNames.push(key);
          			hours.push(example[0][key]["hours"] || example[0][key]["verification"]["hours"] );
               
          }
          console.log(statusNames);
          console.log(hours);

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-08-02
            • 1970-01-01
            • 2017-03-25
            • 2020-08-03
            • 1970-01-01
            • 1970-01-01
            • 2021-02-04
            • 1970-01-01
            相关资源
            最近更新 更多