Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从嵌套数组到对象数组_Javascript_Html - Fatal编程技术网

Javascript 从嵌套数组到对象数组

Javascript 从嵌套数组到对象数组,javascript,html,Javascript,Html,我有一个这样的嵌套数组 array = [[1, 698],[32, 798],[69, 830],[95, 500]] 我想要一个以这种格式返回结果的函数 [ { id: 1, score: 698 }, { id: 32, score: 798 }, { id: 69, score:830 }, ..... the rest of the ar

我有一个这样的嵌套数组

array = [[1, 698],[32, 798],[69, 830],[95, 500]]
我想要一个以这种格式返回结果的函数

[
    {
        id: 1,
        score: 698
    },
    {
        id: 32,
        score: 798
    },
    {
        id: 69,
        score:830
    },
  ..... the rest of the array
]
我确实使用了for循环,但没有成功,我不知道如何处理这种情况

for(var i = 0; i <= array.lenght ; i++){
    var obj={}
    var res = []
    res.push(array[i])
}

for(var i=0;i您可以利用ES6语法的强大功能:

var数组=[
[1, 698],
[32, 798],
[69, 830],
[95, 500],
];
var res=array.map(([id,score])=>({id,score}));

console.log(res);
使用
数组.prototype.map
解构
速记对象literal

var数组=[[1698]、[32798]、[69830]、[95500];
var result=array.map(([id,score])=>({id,score}));
console.log(结果);
您可以与以下内容一起使用:

const数组=[[1698]、[32798]、[69830]、[95500];
const result=array.map(([id,score])=>({id,score}));

console.log(result);
首先需要一个函数,该函数接受2个元素的数组并返回一个对象

const objBuilder = arr => return { id: arr[0], score: arr[1] }
您可能希望添加错误处理,但这是基本想法

接下来,您需要迭代数组,将每个值(2个元素数组)转换为一个对象。这称为值映射,js本机支持它

const arrayOfObjects =  array.map(objBuilder)
有关地图功能的更多信息,请参见:

许多人的回答都建议
.map(([id,score])=>({id,score}))
非常好。但是如果您必须经常这样做,您可能需要编写一个可重用的函数,使其更具声明性。为此,类似的方法可能会奏效:

const zipObject=names=>values=>names.reduce(
(obj,name,idx)=>(obj[name]=值[idx],obj),{}
)
常量数组=[[1698],[32798],[69830],[95500]]

log(array.map(zipObject(['id','score']))
只是为了澄清这不起作用的原因:您在每次迭代中从头开始重新创建
res
,这样您就不会在每次我喜欢您的方法时都将映射数据推送到同一个数组中,但我不确定OP是否能够理解it@AbdeslemCharif:谢谢。你很可能是对的,但我更喜欢推f如果可能的话,多功能的方法。
const arrayOfObjects =  array.map(objBuilder)