我有一个对象数组。我想获取键和值并打印数据。例如。我有ID,用户名和密码,我想要用户名和密码。
[
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
输出应为
name : admin
password : admin,
name : user
password : user,
name : superadmin
password : superadmin
答案 0 :(得分:1)
let data = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
];
var out_data = data.reduce((a, b) => a + 'name: ' + b.name + ', password: ' + b.password + ' ', '');
console.log(out_data);
答案 1 :(得分:0)
鉴于您拥有的数组,您只需要遍历它:
end if
答案 2 :(得分:0)
var arr = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
[![enter image description here][1]][1]
Loop through the array
arr.forEach(function(data) {
console.log('name', data.name);
console.log('password', data.password);
})
[1]: https://i.stack.imgur.com/uYA9i.png
答案 3 :(得分:0)
To iterate key values dynamically, you have to iterate object.
let arr = [
{"id":1,"name":"admin","password":"admin","role":"Admin"},
{"id":2,"name":"user","password":"user","role":"User"},
{"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
];
arr.forEach((item, i) => {
for(let key in item) {
console.log(`${key}: ${item[key]}`);
}
});
If you would like to display only name and password, then you can add a condition.
arr.forEach((item, i) => {
for(let key in item) {
if (key === 'name' || key === "password") {
console.log(`${key}: ${item[key]}`);
}
}
});