数组转化对象数组,如下

Neoo1984
  • 53

let arr = [

    ['apple','banana','orange'],
    ['white','black','green'],
    ['cat','dog']
];

转化为
  let obj = [
    {
        name: "apple",
        age: "banana",
        content:"orange"
    },
    {
        name: "white",
        age: "black",
        content:"green"
    }, {
        name: "cat",
        age: "dog",
        content: ""
    }
];
这种形式
回复
阅读 831
3 个回答
✓ 已被采纳
let result = arr.map(item => ({ name: item[0] || '', age: item[1] || '', content: item[2] || '' }))
       let arr = [
            ['apple','banana','orange'],
            ['white','black','green'],
            ['cat','dog']
       ];
       const keys = ["name", "age", "content"];
       const result =  arr.map((item) => {
            let temp = {};
            keys.forEach((key, index) => {
                temp[key] = item[index] ? item[index] : "";
            });
            return temp;
        });
let arr = [["apple", "banana", "orange"], ["white", "black", "green"], ["cat", "dog"]];
const result = arr.reduce((total, cur) => {
    let [name = "", age = "", content = ""] = cur;
    total.push({ name, age, content });
    return total;
}, []);
console.log(result);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏