将两个数组转换为对象-JavaScript

时间:2018-10-29 22:53:13

标签: javascript arrays json reactjs javascript-objects

在将两个数组变成一个数组对象时遇到问题。

这是我的第一个数组;我们称之为“ ”。我想使该数组上的每个项目成为对象键。

["name", "age", "gender", "status"]

这是我的第二个数组,将作为值。我们称之为“ 标题

[["Luke May", 43, "male", "married"]
["Sarah Saw", 54, "female", "single"]
["Magac gose", 51, "male", "single"]]

我希望我的对象看起来像这样。我们称之为“ arrValues

[
   {name: "Luke May", age: 43, gender: "male", status: "married"}
   {name: "Sarah Saw", age: 54, gender: "female", status: "single"}
   {name: "Magac gose", age: 51, gender: "male", status: "single"}
]

问题是我的代码必须是动态的,这意味着它将完美地将任意两个数组转换为一个对象,就像上面那样。

what I have so far

What I am looking for

到目前为止,这是我的尝试:

var arrh = header
var data = []
    for(var i = 1; i < header.length; i++){
        var dataToInsert = {}
        var values = arrValues[i];

        for(var x = 0; x < header.length; x++){
            var kx = header[x];
            dataToInsert[kx] = arrValues[x]
        }
        data.push(dataToInsert)
}

3 个答案:

答案 0 :(得分:0)

const keys = ["name", "age", "gender", "status"];

const obj = [
  ["Luke May", 43, "male", "married"],
  ["Sarah Saw", 54, "female", "single"],
  ["Magac gose", 51, "male", "single"]
].map(x => {
  let m = {};
  for (let i = 0; i < keys.length; i++) m[keys[i]] = x[i];
  return m;
});
console.log(obj)

答案 1 :(得分:0)

假设第二个数组内部的值数量与键的数量完全匹配并且它们的顺序相同,则可以按如下所示使用两个循环,外部循环用于循环第二个数组,内部循环用于每个数组中的值。

var results = [
  ["Luke May", 43, "male", "married"],
  ["Sarah Saw", 54, "female", "single"],
  ["Magac gose", 51, "male", "single"]
];
var keys = ["name", "age", "gender", "status"];

var objectArray = []; // your result

results.forEach(r => {
  let obj = {};
  r.forEach((r, i) => {
obj[keys[i]] = r;
  });
  objectArray.push(obj);
});

console.log(objectArray);

答案 2 :(得分:0)

下面的答案只是提供一个想法,让我们了解如何使用简单的JavaScript(带有for循环)解决此问题

            V1       V2                  V3                  V4              V5              V6           V7 
1: Dining Room  Pre-War Laundry in Building          Dishwasher Hardwood Floors    Dogs Allowed Cats Allowed 
2:     Doorman Elevator Laundry in Building          Dishwasher Hardwood Floors          No Fee         <NA> 
3:     Doorman Elevator Laundry in Building     Laundry in Unit      Dishwasher Hardwood Floors         <NA> 
4:        <NA>     <NA>                <NA>                <NA>            <NA>            <NA>         <NA> 
5:     Doorman Elevator      Fitness Center Laundry in Building            <NA>            <NA>         <NA> 

,输出将是

var keys = ["name", "age", "gender", "status"];
var header = [
     ["Luke May", 43, "male", "married"],
     ["Sarah Saw", 54, "female", "single"],
     ["Magac gose", 51, "male", "single"]
];

for(i=0; i<header.length; i++){
  var obj={};
  for (j=0; j<keys.length; j++){
      obj[keys[j]]=header[i][j];
   }
  arrValues.push(obj);
}

arrValues;