这就是我的流程。我将使用第一个数组,将值作为对象键分配给我的模板。然后,我想使用该模板,将下一个数组的元素分配为其值,然后将其推入最终响应对象。然后,我将继续执行此操作,直到到达响应数组的末尾。我本质上想将其转换为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
}
答案 0 :(得分:2)
您想要的输出无效。您在整个事情中都有{}
,但这是针对对象的,它们需要成对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));
答案 1 :(得分:0)
也许是这样
var oData = [
[
"POP",
"GEONAME",
"state"
],
[
"4863300",
"Alabama",
"01"
],
[
"741894",
"Alaska",
"02"
],
[
"6931071",
"Arizona",
"04"
],
[
"2988248",
"Arkansas",
"05"
],
[
"39250017",
"California",
"06"
]
];
var oResult = [];
var columns = null;
oData.forEach(function(data) {
if (columns === null) {
columns = data;
} else {
var oEntry = {};
oResult.push(oEntry);
data.forEach(function(d, i) {
oEntry[columns[i]] = d;
});
}
});
console.log(oResult);
答案 2 :(得分:0)
使用https:/link3.jpg
获取和删除列名,然后使用shift()
数组的其余部分并在列上使用map()
创建每个对象
reduce()
let cols = data.shift()
let res = data.map(arr => cols.reduce((a, c, i) => (a[c] = arr[i], a), {}))
console.log(res)
答案 3 :(得分:0)
您可以将键和值分成单独的数组,然后使用Array.prototype.map
遍历值,并使用Array.prototype.reduce
构造对象:
const data=[["POP","GEONAME","state"],["4863300","Alabama","01"],["741894","Alaska","02"],["6931071","Arizona","04"],["2988248","Arkansas","05"],["39250017","California","06"]];
const [keys, ...vals] = data;
const result = vals.map(item => item.reduce((all,v,i) => (all[keys[i]] = item[i], all), {}));
console.log(result);