gpt4 book ai didi

javascript - API 响应是数组的数组。第一个数组是对象键值对中的键

转载 作者:行者123 更新时间:2023-12-01 01:51:56 25 4
gpt4 key购买 nike

这就是我的流程。我将采用第一个数组,将值作为对象键分配给我的模板。然后我想使用该模板,将下一个数组的元素作为值分配给它,然后将其推送到最终的响应对象。然后我会继续这样做,直到到达响应数组的末尾。我本质上想将其转换为 JSON,使用第一个响应数组的元素作为所有元素的值。

这是回复:

[
[
"POP",
"GEONAME",
"state"
],
[
"4863300",
"Alabama",
"01"
],
[
"741894",
"Alaska",
"02"
],
[
"6931071",
"Arizona",
"04"
],
[
"2988248",
"Arkansas",
"05"
],
[
"39250017",
"California",
"06"
]
]

这是我想要的输出(键始终是第一个响应索引)

{
{
"POP": "4863300"
"GEONAME": "Alabama"
"state": "01"
}
{
"POP": "741894"
"GEONAME": "Alaska"
"state": "02"
},
{
"POP": "6931071"
"GEONAME": "Arizona"
"state": "04"
},
{
"POP": "2988248"
"GEONAME": "Arkansas"
"state": "05"
},
{
"POP": "39250017"
"GEONAME": "California"
"state": "06"
}
}

这是我到目前为止所拥有的:

function modifyArrayResponse(response) {
// Create template (Assign keys)
let template = {};
let keys = response[0];

// Assign keys to template
for(let i = 0; i < keys.length; i++){
template[keys[i]] = template[i];
}

// Use the template (Assign values)



// Return modified response
}

最佳答案

您想要的输出无效。整个事情都有 {} 围绕,但那是针对对象的,它需要是 key: value 对。你应该想要的是一个对象数组:

[
{
"POP": "4863300"
"GEONAME": "Alabama"
"state": "01"
}
{
"POP": "741894"
"GEONAME": "Alaska"
"state": "02"
},
{
"POP": "6931071"
"GEONAME": "Arizona"
"state": "04"
},
{
"POP": "2988248"
"GEONAME": "Arkansas"
"state": "05"
},
{
"POP": "39250017"
"GEONAME": "California"
"state": "06"
}
]

创建此元素的代码需要循环第一个元素之后的所有元素。

function modifyArrayResponse(response) {
const keys = response[0];
const result = [];
for (let i = 1; i < response.length; i++) {
const obj = {};
keys.forEach((key, index) => obj[key] = response[i][index]);
result.push(obj);
}
return result;
}

var input = [
["POP", "GEONAME", "state"],
["4863300", "Alabama", "01"],
["741894", "Alaska", "02"],
["6931071", "Arizona", "04"],
["2988248", "Arkansas", "05"],
["39250017", "California", "06"]
];

console.log(modifyArrayResponse(input));

关于javascript - API 响应是数组的数组。第一个数组是对象键值对中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51411736/

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