gpt4 book ai didi

javascript - 在javascript中从数组生成多级对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:16:01 25 4
gpt4 key购买 nike

我有一个事件数组,我想在这些数组的对象之间建立关系。数组:

[{
'area': 'punjab',
'site': 'lahore',
'link': 'http: //lahore.com'
}, {
'area': 'punjab',
'site': 'sargodha',
'link': 'http: //sargodha.com'
}, {
'area': 'punjab',
'site': 'multan',
'link': 'http: //multan.com'
} {
'area': 'sindh',
'site': 'karachi',
'link': 'http: //karachi.com'
}]

知道我想让关系变成这样

 {
"area": "punjab",
"site": [
{
"name": "lahore",
"link": [
{
"name": "http://sargodha.com",
}
]
},
{
"name": "sargodha",
"link": [
{
"name": "http://sargodha.com",
}
]
}
]
},
{
"area": "sindh",
"site": [
{
"name": "karachi",
"link": [
{
"name": "http://karachi.com",
}
]
}
}

这是我写的代码:

    function isinarrayfilters(matchingObject, targetArray, key) {
var existindex = -1;
$.each(targetArray, function(index, array) {
if (array.key == matchingObject.key) {
//Object exist in array
existindex = index;
}
});
return existindex;
}

generatedRelationArray = [];
$.each(alertsJson, function(index, alertJson) {
inarrayindex = isinarrayfilters(alertJson.area, relationArray,'area');
if (inarrayindex == -1) {
key = alertJson.site
generatedsites = {
"area": alertJson.area,
"site": []
}
relationArray.push(generatedsites);
}
});

知道任何人指导我如何将网站附加到相关区域。

  • 我必须再次运行循环并尝试检查存在的方法并获取索引并将站点推送到其中吗?

最佳答案

保留格式的答案:

var generate = function(list) {
var resultList = [];
var tmpStoreRef = {};

$.each(list, function(id, item) {
var area = item.area
,site = item.site
,link = item.link;
if (typeof tmpStoreRef[area] === 'undefined') {
tmpStoreRef[area] = {
area: area,
site: []
}
resultList.push(tmpStoreRef[area]);
}
tmpStoreRef[area].site.push({
name: site,
link: link
});
});

return resultList;
};

关于javascript - 在javascript中从数组生成多级对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30890216/

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