gpt4 book ai didi

jquery - 使用 jQuery 组织 JSON 结果

转载 作者:行者123 更新时间:2023-12-01 06:49:45 26 4
gpt4 key购买 nike

我有一个如下所示的 JSON 对象:

data=[{"name":"John Smith",
"favorites":{"color":"orange",
"city":"Paris"}},
{"name":"Jane Baker",
"favorites":{"color":"red",
"city":"San Francisco"}},
{"name":"Tommy Jones",
"favorites":{"color":"blue",
"city":"Paris"}}]

我想用 jQuery 来检查这些结果,并重新构造数据,每个人都会进入一个最喜欢的城市对象(如果它是唯一的,则创建一个新对象,如果不是,则将其放入现有对象中)。像这样...

data=[
{"city":"Paris",
{{"name":"John Smith",
"color":"orange"},
{"name":"Tommy Jones",
"color":"blue"}}
},
{"city":"San Francisco",
{{"name":"Jane Baker",
"color":"red"}}
}]

有人可以帮我解决这个问题吗?

最佳答案

我会这样做:

var newData = [], tempData = {};

for (var i = 0; i < data.length; i++) {

// Extract all the information we need.
var person = data[i],
cityName = person.favorites.city,
personObj = {name: person.name, color: person.favorites.color };

if (tempData[cityName]) {
tempData[cityName].people.push(personObj);
} else {
tempData[cityName] = { people: [personObj] };
}
}

// Sort the data into the required format
for (var city in tempData) {
var people = tempData[city].people;
newData.push({ city: city, people: people });
}

关于jquery - 使用 jQuery 组织 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16744621/

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