在Javascript中组合两个数组以创建JSON

时间:2017-09-13 05:30:15

标签: javascript arrays json

我有两个数组:

passwordConfirm(control: FormControl): {[s: string]: boolean} {
    if (control.value === this.password) {
        return null;
    }
    return { mismatch: true };
}

如何组合它们并使用数据创建JSON以保存以下内容:

headers=['medium','source', 'name']

rows=[
['direct', 'google', 'demoAccount'],
['direct', 'google', 'demoAccount'],
['direct', 'google', 'demoAccount']
]

1 个答案:

答案 0 :(得分:0)

您可以使用array#maparray#reduce



const headers=['medium','source', 'name'];

const rows=[['direct', 'google', 'demoAccount'],['direct', 'google', 'demoAccount'],['direct', 'google', 'demoAccount']];

var result = rows.map((arr) => {
  return arr.reduce((o, n, i) => {
    o[headers[i]] = n;
    return o;
  }, Object.create(null));
});

console.log(result);