javascript - 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
]
对象被复制。一次使用嵌套数组,而其他时间则没有。我只是不想要这种重复。
解决方案
您可以使用Object.keys
,Object.values
或Object.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);
推荐阅读
- html5-video - .mp4 视频无法在移动设备上播放
- android - Ratingbar的最后一颗星星正在被裁剪
- java - 默认情况下登录 Tomcat 网络服务器是异步的吗?
- computational-geometry - 构建多边形的约束 alpha 形状
- c - 为什么这个快速排序算法实现代码会出现分段错误错误?
- python-asyncio - TypeError:对象 NoneType 不能在“等待”表达式中使用
- excel - 如何使用我定义的最后一行作为我的范围的一部分?
- c# - 打印任何希望类的字段名称
- jenkins - 如何在 Jenkins Job DSL 中创建可扩展的基础作业?
- python - 从包含标题和分隔符的文本文件中提取列