首页 > 解决方案 > Object.keys 复制数组 es6 中的对象

问题描述

我有一个这样的对象结构:

vKzGBlblU7hVqIildUIb:
characters: (2) [{…}, {…}]
created_by: "test1234"
deleted_at: null
genre: ""
key: "vKzGBlblU7hVqIildUIb"
main_character: ""
number_of_characters: 2
status: "draft"
summary: "Summary 23"
title: "Titile 23"
uploaded_at: 1531686836601

我尝试使用将这个对象转换为数组,Object.keys但最终在一个数组中有 2 个对象。一个包含内部数组characters,另一个对象不包含数组characters。我得到这样的东西。

0:
    characters: (2) [{…}, {…}]
    created_by: "test1234"
    deleted_at: null
    genre: ""
    key: "vKzGBlblU7hVqIildUIb"
    main_character: ""
    number_of_characters: 2
    status: "draft"
    summary: "Summary 23"
    title: "Titile 23"
    uploaded_at: 1531686836601

1:
    created_by: "test1234"
    deleted_at: null
    genre: ""
    key: "vKzGBlblU7hVqIildUIb"
    main_character: ""
    number_of_characters: 2
    status: "draft"
    summary: "Summary 23"
    title: "Titile 23"
    uploaded_at: 1531686836601

这就是我试图将对象转换为数组的方式。

const array = Object.keys(objs).map((obj, index) => {
      return objs[obj]
    });

我不明白我做错了什么。有什么建议么?

更新: 对象结构很简单:

{
    vKzGBlblU7hVqIildUIb: {
        characters: [{
            name: "",
            id: ""
        }]
        key: "vKzGBlblU7hVqIildUIb"
        //other props listed in the example above
    }
    irufsxKuw9I20pLDa6P7: {
        characters: [{
            name: "",
            id: ""
        }]
        key: "irufsxKuw9I20pLDa6P7"
        //other props listed in the example above
    }
    // so on
}

我期望Object.keys会做的事情:

[
    0: {
        characters: [{
            name: "",
            id: ""
        }]
        key: "vKzGBlblU7hVqIildUIb"
        //other props listed in the example above
    }
    1: {
        characters: [{
            name: "",
            id: ""
        }]
        key: "irufsxKuw9I20pLDa6P7"
        //other props listed in the example above
    }

    // so on
]

但实际发生了什么:

[
    0: {
        characters: [{
            name: "",
            id: ""
        }]
        key: "vKzGBlblU7hVqIildUIb"
        //other props listed in the example above
    }
    1: {
        characters: [{
            name: "",
            id: ""
        }]
        key: "irufsxKuw9I20pLDa6P7"
        //other props listed in the example above
    }
    2: {
        key: "vKzGBlblU7hVqIildUIb"
        //other props listed in the example above
    }
    3: {
        key: "irufsxKuw9I20pLDa6P7"
        //other props listed in the example above
    }
    // so on
]

对象被复制。一次使用嵌套数组,而其他时间则没有。我只是不想要这种重复。

标签: javascriptarraysobjectecmascript-6

解决方案


您可以使用Object.keys,Object.valuesObject.entries:

const obj={vKzGBlblU7hVqIildUIb:{characters:[{name:"",id:""}],key:"vKzGBlblU7hVqIildUIb"},irufsxKuw9I20pLDa6P7:{characters:[{name:"",id:""}],key:"irufsxKuw9I20pLDa6P7"}};

const v1 = Object.keys(obj).map(k => obj[k]);

const v2 = Object.values(obj);

const v3 = Object.entries(obj).map(([_,o]) => o);

console.log(v1);
console.log(v2);
console.log(v3);


推荐阅读