gpt4 book ai didi

javascript - 在 JavaScript 中将 JSON 数据转换为数组

转载 作者:行者123 更新时间:2023-12-02 05:24:30 26 4
gpt4 key购买 nike

我的json数据是这样的:

[{"vehicleType":"car","make":"Dodge","model":"Durango","vin":"R90N8E95UB"},
{"vehicleType":"car","make":"Honda","model":"Accord","vin":"XJLSXU6NA5"},
{"vehicleType":"car","make":"Dodge","model":"Durango","vin":"2UNHFBCQG0"},
{"vehicleType":"car","make":"Volvo","model":"XC90","vin":"J37612ZVEC"},
{"vehicleType":"car","make":"Mercedes","model":"C250","vin":"J5QB24CFGS"},
{"vehicleType":"car","make":"Dodge","model":"Durango","vin":"OB60BC33LF"},
{"vehicleType":"car","make":"Volvo","model":"XC90","vin":"DCA3364SGK"},
{"vehicleType":"car","make":"Volvo","model":"XC60","vin":"FV2HML056G"},
{"vehicleType":"car","make":"BMW","model":"328xi","vin":"IGPP3DQ4SK"},
{"vehicleType":"car","make":"Mercedes","model":"C250","vin":"J5QB24CFGS"},
{"vehicleType":"car","make":"Honda","model":"Accord","vin":"XJLSXU6NA5"},
{"vehicleType":"car","make":"Mercedes","model":"C250","vin":"J5QB24CFGS"},
{"vehicleType":"car","make":"Dodge","model":"Durango","vin":"R90N8E95UB"}]

现在我希望我的数组在 JavaScript 中是这样的:

// Javascript array
var array = [];
array[// vin number od above json array] = // the whole row of that vin number.

例如,

// Javascript array
array["R90N8E95UB"][0]
=[{"vehicleType":"car","make":"Dodge","model":"Durango","vin":"R90N8E95UB"}]
array["R90N8E95UB"][1]
=[{"vehicleType":"car","make":"Dodge","model":"Durango","vin":"R90N8E95UB"}]

等等……

请指教。

谢谢。

最佳答案

您可以迭代并推送到内部数组。

var data = [{ vehicleType: "car", make: "Dodge", model: "Durango", vin: "R90N8E95UB" }, { vehicleType: "car", make: "Honda", model: "Accord", vin: "XJLSXU6NA5" }, { vehicleType: "car", make: "Dodge", model: "Durango", vin: "2UNHFBCQG0" }, { vehicleType: "car", make: "Volvo", model: "XC90", vin: "J37612ZVEC" }, { vehicleType: "car", make: "Mercedes", model: "C250", vin: "J5QB24CFGS" }, { vehicleType: "car", make: "Dodge", model: "Durango", vin: "OB60BC33LF" }, { vehicleType: "car", make: "Volvo", model: "XC90", vin: "DCA3364SGK" }, { vehicleType: "car", make: "Volvo", model: "XC60", vin: "FV2HML056G" }, { vehicleType: "car", make: "BMW", model: "328xi", vin: "IGPP3DQ4SK" }, { vehicleType: "car", make: "Mercedes", model: "C250", vin: "J5QB24CFGS" }, { vehicleType: "car", make: "Honda", model: "Accord", vin: "XJLSXU6NA5" }, { vehicleType: "car", make: "Mercedes", model: "C250", vin: "J5QB24CFGS" }, { vehicleType: "car", make: "Dodge", model: "Durango", vin: "R90N8E95UB" }],
result = Object.create(null),
keys;

data.forEach(function (a) {
result[a.vin] = result[a.vin] || [];
result[a.vin].push(a);
});

keys = Object.keys(result);

console.log(keys);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 在 JavaScript 中将 JSON 数据转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42579906/

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