我在for循环内有for循环...,我的数组输出是嵌套数组cameraManager = new CameraManager(this);
etNotice = findViewById(R.id.point_c_notice);
getValidations().add(new TextEmptyValidation(this, etNotice));
etNotice.addTextChangedListener(getLastValidation());
tiAddress = findViewById(R.id.point_c_address);
tiTel = findViewById(R.id.point_j_tel);
tiTel.setAutoLinkMask(Linkify.PHONE_NUMBERS);
tiTel.setMovementMethod(new ScrollingMovementMethod());
,但我需要
[[{...}]]
在这种情况下,有什么方法可以使这个数组没有嵌套数组吗?
这是我的代码... 我有用户,每个用户我都需要添加新的对象数组
[{...}]
用户可以扮演多个角色,但是由于数据库结构的原因,我需要在用户对象中发送带有对象的数组
users = [{
name: "user1"
role: ["admin", "tester", "viewer"]
},{
name: "user2"
role: ["admin", "tester", "viewer"]
}]
userRole: any[]=[];
for (let user of users){
for (let u of user.role){
this.userRole.push({
name: user.name,
role: u
})
}
this.data.push(this.userRole)
}
但是我明白了
{ "name": "user1",
"role": [{
"role" : "admin",
"user" : "user1"
},{
"role" : "tester",
"user" : "user1"
},{
"role" : "view",
"user" : "user1"
}]
}
我尝试使用{ "name": "user1",
"role": [ // nested array
[{
"role" : "admin",
"user" : "user1"
},{
"role" : "tester",
"user" : "user1"
},{
"role" : "view",
"user" : "user1"
}]
]
}
,但还是一样
答案 0 :(得分:3)
您可以简单地使用两个map
let users = [{name: "user1",role: ["admin", "tester", "viewer"]}, {name: "user2",role: ["admin", "tester", "viewer"]}]
let final = users.map(({name,role})=>{
return {
name,
role: role.map(user=>({name,user}))
}
})
console.log(final)
要使您的代码正常工作,您需要定义两个变量,一个变量保存最终值,另一个变量保存userRole
,用于特定用户,
const users = [{name: "user1",role: ["admin", "tester", "viewer"]}, {name: "user2", role: ["admin", "tester", "viewer"]}]
const final = []
for (let user of users) {
const userRole = [];
for (let u of user.role) {
userRole.push({
name: user.name,
role: u
})
}
final.push({name:user.name, role: userRole})
}
console.log(final)
答案 1 :(得分:1)
我对您的代码进行了一些更改。您正在创建新角色的每个循环中,我都认为this.data是一个userRole数组?因此,您可以将其添加到数据数组的每个循环中。
for (let user of users){
for (let u of user.role){
const userRole= { name: user.name, role: u};
this.userRole.push(userRole);
this.data.push(userRole)
}
}
答案 2 :(得分:1)
请使用flatMap:
var data = { "name": "user1",
"role": [ // nested array
[{
"role" : "admin",
"user" : "user1"
},{
"role" : "tester",
"user" : "user1"
},{
"role" : "view",
"user" : "user1"
}]
]
};
data.role = data.role.flatMap(data => data);
console.log("print data object");
console.log(data)
答案 3 :(得分:1)
c:> rman user/password@mydb
rman> backup database plus archivelog delete all input;
rman> quit
答案 4 :(得分:0)
为什么不在第二个for循环中使用“ u”来添加角色数组?
答案 5 :(得分:0)
这就是答案,@@ CodeManiac用户,他给了我一种思考的方式...
我需要将项目推入第二个for-loop
...,现在一切正常,如我所料
for (let user of users){
for (let u of user.role){
this.data.push(name: user.name, role: u)
}
}