如何使用2个数组的键和值创建新数组?

时间:2018-12-23 18:07:59

标签: javascript jquery html5

我有2个数组,一个用于key,另一个用于value

要使用这些数组创建新数组。

键:[01, 02, 03]
值:["hi", "hello", "welcome"]
我需要的输出:

[ 
  {"key": "1","value":"hi"},
  {"key": "2","value":"hello"},
  {"key": "3","value":"welcome"} 
]    

如何通过这种方式获得结果?

我的代码:

output = key.map(function(obj, index){
      var myObj = {};
      myObj[value[index]] = obj;
      return myObj;
    })    

结果:

 [
 {"1","hi"},
 {"2","hello"},
 {"3","welcome"} 
    ]

4 个答案:

答案 0 :(得分:5)

const keys = [01, 02, 03];
const values = ['hi', 'hello', 'welcome'];

const res = keys.map((key, ind) => ({ 'key': ''+key, 'value': values[ind]}));
console.log(res);

对于以下对象fromEntries的方法也有建议,它可以完全满足您的要求,但是主要浏览器尚不支持它:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

答案 1 :(得分:1)

    var myArray = [];  
    var keys = [45, 4, 9];  
    var cars = ["Saab", "Volvo", "BMW"];  
    cars.forEach(myFunction);  
    var txt=JSON.stringify(myArray);  
    document.getElementById("demo").innerHTML = txt;  
      
    function myFunction(value,index,array) {  
        var obj={ key : keys[index], value : value };  
        myArray.push(obj);  
    }  
    <p id="demo"></p>  

答案 2 :(得分:0)

您可以拍摄具有任意数量的属性的对象并映射新对象。

var key = [1, 2, 3],
    value = ["hi", "hello", "welcome"],
    result = Object
        .entries({ key, value })
        .reduce((r, [k, values]) => values.map((v, i) => Object.assign(
            {},
            r[i],
            { [k]: v }
        )), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

在这里,您还可以使用reduce()

let keys = [01, 02, 03];
let values = ['hi', 'hello', 'welcome'];

let newArray = keys.reduce((res, curr, idx) => {
    res.push({'key': curr.toString(), 'value': values[idx]});
    return res;
}, []);

console.log(newArray);