gpt4 book ai didi

javascript - 从多个数据 JSON 数组写入响应

转载 作者:行者123 更新时间:2023-11-28 02:20:26 25 4
gpt4 key购买 nike

例如,如果我输入 sicans,我会收到来自 API 的响应,如下所示:

{
"data": {
"Data1": [{
"name": "sicans",
"phone_number": "01234",
"email": "i@a.a",
"status": "ACTIVE",
}],
"Data2": [],
"Data3": [],
"Data4": []
}
}

我需要捕获数据然后写入响应。我试过如下所示的 console.log,但它是空的。你知道我如何从响应中得到 name 响应吗?

$.ajax({
url: api_url + 'search?keyword=' + pencarian,
type: 'GET',
success: function(response) {
for (var i = 0; i < response.data.length; i++) {
var name = response.data[i].Data1.name;
console.log(name)
}
}
})

谢谢

最佳答案

response.dataObject 类型。因此,如果您编写 response.data[i],它会返回 undefined,因为 response.data 没有整数键。

var response = {
"data": {
"Data1": [{
"name": "sicans",
"phone_number": "01234",
"email": "i@a.a",
"status": "ACTIVE",
}],
"Data2": [{
"name": "sicans2",
"phone_number": "01234",
"email": "i@a.a",
"status": "ACTIVE",
}],
"Data3": [{
"name": "sicans3",
"phone_number": "01234",
"email": "i@a.a",
"status": "ACTIVE",
}],
"Data4": [{
"name": "sicans4",
"phone_number": "01234",
"email": "i@a.a",
"status": "ACTIVE",
}]
}
}

//Trying to access with integer key. Will return "undefined"
console.log(response.data[0]);


// This example is using "Object.keys()"
console.log('With Object.keys()');
Object.keys(response.data).forEach((key) => {
var name = response.data[key][0].name;
// ^^ this is here because Data1, Data2 etc. are of type Array. We need to get first element
console.log(key, name)
});


// This example is using "Object.values()"
console.log('With Object.values()');
Object.values(response.data).forEach((data) => {
var name = data[0].name;
// ^^ this is here because Data1, Data2 etc. are of type Array. We need to get first element
console.log(name)
});

关于javascript - 从多个数据 JSON 数组写入响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57972838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com