有没有一种简便的方法将带有第一个数组标题的字符串数组转换为对象数组?

3

有没有一种简便的方法,可以将带有标题的字符串数组数组(如下所示的输入)转换为对象数组(如下所示的预期输出)?

虽然使用for循环可以实现这一目标,但我正在寻找任何简洁且优化的解决方案来完成此任务。

如果有任何易于实现且优化的方法,请让我知道。

输入

enter image description here

预期输出

[
    {
        "Name": "Name 1",
        "Age": "Age 1",
        "Location": "Location 1"
    },
    {
        "Name": "Name 2",
        "Age": "Age 2",
        "Location": "Location 2"
    }
]
[
  ['fromAge', 'toAge', 'gender', 'institutionalRaf'],
  [0, 10, 'F', '1.5'],
  [11, 20, 'F', '2.5']
]

期望输出:

[{
   fromAge : 0,
   toAge: 10,
   gender: "F",
   institutionalRaf : "1.5"
},
{
   fromAge : 11,
   toAge: 20,
   gender: "F",
   institutionalRaf : "2.5"
}
...
]

1
请将以下与编程有关的内容从英语翻译成中文。仅返回翻译后的文本:请发布原始数据而不是图片。 - Code Maniac
如果可以的话,请将您的实际代码作为文本编辑到您的问题中-仅有代码图像繁琐且困难进行处理和调试。这迫使那些本来很乐意帮助您的人首先转录您的图像,这是浪费时间。 - CertainPerformance
5个回答

3
您可以将键和值分开,并将值映射为带有键的对象。

var array = [['fromAge', 'toAge', 'gender', 'institutionalRaf'], [0, 10, 'F', '1.5'], [11, 20, 'F', '2.5']],
    [keys, ...values] = array,
    result = values.map(a => Object.assign(...keys.map((k, i) => ({ [k]: a[i] }))));

console.log(result);


3

你可以使用mapreduce

  • 将第一个元素作为header,其余元素作为values
  • 遍历values数组,对于每个元素,构建一个对象,其中键来自header,值来自element

let data = [["fromAge","toAge","gender","institutionalRaf"],["1",'4','m','12'],["4",'12','f','22'],["10",'20','m','109']]
let [header,...values] = data

let final = values.map(v=> {
  return v.reduce((op,inp,index)=>{
    op[header[index]] = inp
    return op
  },{})
})

console.log(final)


2
我会把第一个键的数组移出来,然后使用.map创建条目并使用Object.fromEntries创建对象:最初的回答。

const arr = [
  ['a', 'b', 'c'],
  [1, 2, 3],
  [4, 5, 6]
];

const keys = arr.shift();
const output = arr.map(values =>
  Object.fromEntries(
    values.map((value, i) => [keys[i], value])
  )
);

console.log(output);

Object.fromEntries 是一个相对较新的方法。在旧的环境中,可以使用 polyfill 或者使用 reduce 方法创建对象代替:

const arr = [
  ['a', 'b', 'c'],
  [1, 2, 3],
  [4, 5, 6]
];

const keys = arr.shift();
const output = arr.map(values => (
  values.reduce((a, value, i) => {
    a[keys[i]] = value;
    return a;
  }, {})
));

console.log(output);


1
如果密钥是固定的,我们可以使用以下简单方法:

let arr=[
  ['fromAge', 'toAge', 'gender', 'institutionalRaf'],
  [0, 10, 'F', '1.5'],
  [11, 20, 'F', '2.5']
];
let arr1=arr.slice();
let x=arr1.shift();
let x1=arr1.map(a=>(
                    {
                      [x[0]]:a[0],
                      [x[1]]:a[1],
                      [x[2]]:a[2],
                      [x[3]]:a[3],
                      
                    }
                   )
                 )
console.log(x1);


1

Use destructuring, map and reduce

const array = [
  ['fromAge', 'toAge', 'gender', 'institutionalRaf'],
  [0, 10, 'F', '1.5'],
  [11, 20, 'F', '2.5']
]
const [keys, ...values] = array
const result = values.map((value) => value.reduce((a, b, index) => ({...a, [keys[index]]: b}), {}), [])
console.log("result",result)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接