从数组合并到对象后的 Javascript

const arrays = [

  [123, "string1"],

  [4564564, "string2"],

  [392341231, "string3"],

  [1665342, "String4", 334934543, "string5"]

];


const s = arrays.reduce((acc, val) => {

  return acc.concat(val);

});


// output: 

// [123, "string1", 4564564, "string2", 392341231, "string3", 1665342, "String4", 334934543, "string5"]

扁平化阵列后,输出的是一个number一个string的,我尝试使用reduce,使物体像


{

123: "string1",

4564564: "string2",

392341231: "string3",

1665342:  "String4",

334934543: "string5"

}

.reduce(function(acc, cur, i) {

  acc[cur] = cur;

  return acc;

}, {});

输出错误,如何分离number和string内部reduce?谢谢


猛跑小猪
浏览 148回答 3
3回答

元芳怎么了

您可以通过映射各个索引并将它们全部分配给一个新对象来轻松完成,这将减少您对中间步骤的需求const arrays = [  [123, "string1"],  [4564564, "string2"],  [392341231, "string3"],  [1665342, "String4", 334934543, "string5"]];console.log( Object.assign( {}, ...arrays.map( i => ({[i[0]]: i[1] }) ) ) );

红糖糍粑

你必须保持两个键和值。迭代每个子数组,将第二项(值)分配到第一项(键)处的累加器:const arrays = [&nbsp; [123, "string1"],&nbsp; [4564564, "string2"],&nbsp; [392341231, "string3"],&nbsp; [1665342, "String4", 334934543, "string5"]];const obj = arrays.reduce((a, subarr) => {&nbsp; for (let i = 0; i < subarr.length; i += 2) {&nbsp; &nbsp; a[subarr[i]] = subarr[i + 1];&nbsp; }&nbsp; return a;}, {});console.log(obj);

翻过高山走不出你

你可以这样做:const arrays = [&nbsp; [123, "string1"],&nbsp; [4564564, "string2"],&nbsp; [392341231, "string3"],&nbsp; [1665342, "String4", 334934543, "string5"]];const s = arrays.reduce((acc, val) => {&nbsp; let i = 0&nbsp; while (i < val.length) {&nbsp; &nbsp; acc[val[i]] = val[i + 1];&nbsp; &nbsp; i += 2&nbsp; }&nbsp; return acc;},{});console.log( s )
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript