基于此现有数组对象创建新的多维数组 [英] Create new multidimensional array based on this existing array objec
本文介绍了基于此现有数组对象创建新的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我被迫基于此现有数组对象构造一个新的多维数组
I'm stuck to construct a new multidimensional array based on this existing array object
acl:[
{
view:true,
update:true,
remove:true,
userId:1,
username:"Mike"
},
{
view:true,
update:true,
remove:false,
userId:2,
username:"Joe"
},
{
view:true,
update:false,
remove:false,
userId:3,
username:"Lim"
}
]
将基于布尔属性构造新对象(如果这些布尔值等于true).新的数组看起来像这样
The new object will be constructed based on the boolean properties(if these boolean is equal to true). The new array will look like this
acl:[
{
view:[
{username:"Mike", userId:1},
{username:"Joe", userId:2},
{username:"Lim", userId:3}
]
update:[
{username:"Mike", userId:1},
{username:"Joe", userId:2}
]
remove:[
{username:"Mike", userId:1}
]
我坚持在迭代内部构造逻辑.也许有人可以给我一个提示.
Im stuck on constructing the logic inside the iteration. Maybe someone could give me a hint on this.
推荐答案
const acl = [{"view":true,"update":true,"remove":true,"userId":1,"username":"Mike"},{"view":true,"update":true,"remove":false,"userId":2,"username":"Joe"},{"view":true,"update":false,"remove":false,"userId":3,"username":"Lim"}]
function multi_dim (array) {
const res = {
view: [],
update: [],
remove: []
}
const keys = Object.keys(array[0])
for (let i = 0; i < array.length; i++) {
keys.forEach(function (key) {
if (key !== 'username' && key !== 'userId') {
if (array[i][key]) {
res[key].push({
username: array[i].username,
userId: array[i].userId
})
}
}
})
}
return res
}
let obj = multi_dim(acl) // returns object. Push to array if so desired
console.log(obj)
// => result
// {
// "view": [
// {
// "username": "Mike",
// "userId": 1
// },
// {
// "username": "Joe",
// "userId": 2
// },
// {
// "username": "Lim",
// "userId": 3
// }
// ],
// "update": [
// {
// "username": "Mike",
// "userId": 1
// },
// {
// "username": "Joe",
// "userId": 2
// }
// ],
// "remove": [
// {
// "username": "Mike",
// "userId": 1
// }
// ]
// }
这篇关于基于此现有数组对象创建新的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文