英文:
I cant get array value from my server responce
问题
I have translated the code portion for you:
我通过服务器收到一个字典响应。
console.log(responce) 返回以下内容:
{"filters":{
"Facture": [
"Магма (Тычок)",
"Тонкий кирпич",
"Гладкий",
"Крафт",
"Магма"
],
"Color": [
"Беж",
"Черный",
"Амстердам",
"Лондон Брик",
"Мюнхен",
"Сити Брик"
],
"Name": [
"Облицованный кирпич стандартный пустотелый",
"Тонкий колотый с ф. 180/11"
]
}}
但是当我尝试使用以下代码访问值时:
console.log(xhr.responseText);
const response = xhr.responseText;
console.log(response);
const myObj = JSON.parse(response);
console.log(myObj);
var names = myObj.Name.map(name => name.trim());
var types = myObj.Facture.map(type => type.trim());
var colors = myObj.Color.map(color => color.trim());
console.log(names);
console.log(types);
console.log(colors);
如果在脚本内部创建此对象,它可以正常工作,但是当我通过响应获取对象时,它不起作用。我尝试了几乎所有方法,包括更改服务器发送的数据和使用不同的代码访问值,但仍然返回undefined。请帮助我获取值...
英文:
I have my server respond me with an dictionary.
The console.log(responce) returns this:
{"filters":{
"Facture": [
"Магма (Тычок)",
"Тонкий кирпич",
"Гладкий",
"Крафт",
"Магма"
],
"Color": [
"Беж",
"Черный",
"Амстердам",
"Лондон Брик",
"Мюнхен",
"Сити Брик"
],
"Name": [
"Облицованный кирпич стандартный пустотелый",
"Тонкий колотый с ф. 180/11"
]
}}
But when i try to access the value with this code:
console.log(xhr.responseText);
const response = xhr.responseText;
console.log(response);
const myObj = JSON.parse(response);
console.log(myObj);
var names = myObj.Name.map(name => name.trim());
var types = myObj.Facture.map(type => type.trim());
var colors = myObj.Color.map(color => color.trim());
console.log(names);
console.log(types);
console.log(colors);
It returns undefined in the console. Please help me get the value....
The only clue that i got, that if i create this object inside of my script it works correct, but doesnt work when i get the object through the responce
I tried literally everything:
Changing the data i send by the server
Accessing the value with different code...
答案1
得分: 1
将这行代码更改为:
const myObj = JSON.parse(response).filters;
因为你要查找的值似乎在属性filters内。
编辑
请注意,评论中提到服务器返回的是"{...}"而不是{...},因此我们不得不进行双重解析:
const myObj = JSON.parse(JSON.parse(response)).filters;
如果你有服务器/后端的控制权,更好的解决方案是在那里进行修复。
英文:
Change this line:
const myObj = JSON.parse(response);
to
const myObj = JSON.parse(response).filters;
since the values you look for seem to be inside the property filters.
Edited
See, comments - it turns out the server returned "{...}" rather than {...} so we hade to double parse it:
const myObj = JSON.parse(JSON.parse(response)).filters;
A better solution if you have control of the server/backend would be to fix this there.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论