我有一个对象数组,我想从键 viewerId
的值中“挑选”一个新数组。我还想将 viewerId
键的名称更改为 userId
。这是我用 lodash 所做的:
const viewerList = [{
"id": 1,
"viewerId": 5,
"status": true
},
{
"id": 2,
"viewerId": 8,
"status": true
},
{
"id": 3,
"viewerId": 6,
"status": true
},
{
"id": 4,
"viewerId": 9,
"status": true
}
]
var result = []
_.each(viewerList, (o) => {
result.push(_.pick(o, 'viewerId'))
})
result = result.map(function(item) {
return {
userId: item.viewerId
}
});
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
我分两步进行。这可以优化吗?
最佳答案
您可以在一条语句中执行以下操作:
const viewerList = [{
"id": 1,
"viewerId": 5,
"status": true
},
{
"id": 2,
"viewerId": 8,
"status": true
},
{
"id": 3,
"viewerId": 6,
"status": true
},
{
"id": 4,
"viewerId": 9,
"status": true
}
]
// The same logic in a single statement
var result = viewerList.map(function(item) {
return { userId : item.viewerId}
})
console.log(result)
这适用于所有浏览器 ie9 及更高版本。有关正在使用的 .map()
函数的更多信息,see this
关于JavaScript:按键选择旧数组并重命名新数组中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52256747/