Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Chuyển mảng thành mảng đối tượng bằng map() và reduce() trong JavaScript

Giả sử chúng ta có mảng lồng nhau như sau:

const arr = [    [       ['juice', 'apple'], ['maker', 'motts'], ['price', 12]    ],    [       ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11]    ] ]; 

Chúng ta cần viết hàm JavaScript nhận mảng như vậy và trả về mảng mới các đối tượng được xây dựng dựa trên mảng đầu vào.

Với mảng trên, đầu ra sẽ trông như:

const output = [    {juice: 'apple', maker: 'motts', price: 12},    {juice: 'orange', maker: 'sunkist', price: 11} ];

Ví dụ

Mã cho việc này:

const arr = [    [       ['juice', 'apple'], ['maker', 'motts'], ['price', 12]    ],    [       ['juice', 'orange'], ['maker', 'sunkist'], ['price', 11]    ] ]; const arrayToObject = arr => {    let res = [];    res = arr.map(list => {       return list.reduce((acc, val) => {          acc[val[0]] = val[1];          return acc;       }, {});    });    return res; }; console.log(arrayToObject(arr));

Đầu ra

Kết quả trên console:

[    { juice: 'apple', maker: 'motts', price: 12 },    { juice: 'orange', maker: 'sunkist', price: 11 } ][    { juice: 'apple', maker: 'motts', price: 12 },    { juice: 'orange', maker: 'sunkist', price: 11 } ]