不仅仅是在 JavaScript 中从数组转换为对象,我想省略特定字段并将它们转换为对象。
这是我的输入数据。
taggedItems = [
{id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},
{id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},
{id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'},
]
这里是预期的输出
taggedOUtput = {
0: {id:0, left:100, top:100, thumbSize:100},
1: {id:1, left:150, top:150, thumbSize:100},
2: {id:2, left:200, top:200, thumbSize:100},
}
我们如何有条件地将数组转换为对象
最佳答案
只需使用Object.assign
方法即可。
let taggedItems = [{id:0, left:100, top:100, thumbSize:100, image: 'b', url: 'y'},{id:1, left:150, top:150, thumbSize:100, image: 'd', url: 'x'},{id:2, left:200, top:200, thumbSize:100, image: 'f', url: 'w'}]
console.log(Object.assign({},taggedItems.map((item) =>({ id:item.id, left:item.left, top:item.top, thumbSize:item.thumbSize }))));
关于javascript - 如何有条件地将数组转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47634745/