[英]JavaScript converting an object to an array
I've researched for about a day and haven't had any luck. 我研究了大约一天,没有任何运气。 I'm trying to access the object properties to simply add it to a typed class in JavaScript. 我试图访问对象属性以将其简单地添加到JavaScript中的类型化类中。 How can i accomplish this? 我怎样才能做到这一点? This is the object im receiving: 这是我收到的对象:
And this my code resulting in the following error: 这是我的代码导致以下错误:
Object.keys(selected).forEach(function (key) {
console.log(selected[key]);
});
Error: 错误:
ERROR TypeError: Cannot convert undefined or null to object 错误TypeError:无法将未定义或null转换为对象
Any help is most appreciated as I've come to here as a last resort. 非常感谢您的帮助,因为我作为不得已来到这里。
selected looks like this: 所选内容如下:
Object.keys(selected)... the selected in json string: Object.keys(selected)...在json字符串中选择的内容:
{
"selected": [
{
"Id": 4,
"Type": 0,
"Image": "",
"Name": "TestName",
"Roles": "TestRole",
"Facility": "TestFacil"
}
]
}
The variable selected is an array, you can try this: 选择的变量是一个数组,您可以尝试以下操作:
selected.forEach(
item=>
Object.keys(item).forEach(function (key) {
console.log(item[key]);
})
)
It could also be: 也可能是:
selected.selected.forEach(
In your question it's not clear what the name is of the value you are logging the json string of. 在您的问题中,尚不清楚您正在记录json字符串的值的名称是什么。
let data = { "selected": [ { "Id": 4, "Type": 0, "Image": "", "Name": "TestName", "Roles": "TestRole", "Facility": "TestFacil" } ] } let arr = []; for (var key in data) { arr.push(data[key]); } console.log(arr)
or you can use that if you wanna convert the whole object to arrays
of arrays
或者如果您想将整个对象转换为arrays
arrays
,则可以使用它
let data = { "selected": [ { "Id": 4, "Type": 0, "Image": "", "Name": "TestName", "Roles": "TestRole", "Facility": "TestFacil" } ] } var arr = []; var i =0; for( var key in data){ var innerArr = [key]; arr.push(innerArr) for(var values in data[key]){ for(var keys in data[key][values]){ var innerArr3 = [keys]; innerArr.push(innerArr3) innerArr3.push(data[key][values][keys]) } } } console.log(arr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.