gpt4 book ai didi

javascript - 从现有对象创建新的数组对象

转载 作者:行者123 更新时间:2023-11-27 23:33:08 25 4
gpt4 key购买 nike

我有一个从正在使用的服务返回的 json 文件。我无法控制该服务,因此无法更改 json 文件的结构。该文件看起来像:

menu":[    
{
"section":"theMobileMenu",
"key":"menuItem1Title",
"content":"Mobile context and principles"
},
{
"section":"theMobileMenu",
"key":"menuItem1Link",
"content":"/mobile/index.html"
},
{
"section":"theMobileMenu",
"key":"menuItem2Title",
"content":"Global guidelines"
},
{
"section":"theMobileMenu",
"key":"menuItem2Link",
"content":"/mobile/global-guidelines.html"
},
{
"section":"theMobileMenu",
"key":"menuItem3Title",
"content":"First impressions"
},
{
"section":"theMobileMenu",
"key":"menuItem3Link",
"content":"/mobile/first-impressions.html"
}
]

我想创建一个如下所示的对象数组

    "menu":[
{
"title":"Mobile context and principles",
"link":"/mobile/index.html"
},
{
"title":"Global guidelines",
"link":"/mobile/global-guidelines.html"
},
{
"title":"First impressions",
"link":"/mobile/first-impressions.html"
}
]

我尝试过类似的方法:

var newData = []
var curData = {};
var x = 1;

$.each(data.menu, function(i, val) {
if(val.key == 'menuItem'+x+'Link'){
curData.link = val.content;
}
if(val.key == 'menuItem'+x+'Title'){
curData.title = val.content;
}
newData.push(curData)
curData = []
x++;
})

这效果不太好。关于如何解决这个问题有什么想法吗?

最佳答案

试试这个:

var data = [{
"section": "theMobileMenu",
"key": "menuItem1Title",
"content": "Mobile context and principles"
}, {
"section": "theMobileMenu",
"key": "menuItem1Link",
"content": "/mobile/index.html"
}, {
"section": "theMobileMenu",
"key": "menuItem2Title",
"content": "Global guidelines"
}, {
"section": "theMobileMenu",
"key": "menuItem2Link",
"content": "/mobile/global-guidelines.html"
}, {
"section": "theMobileMenu",
"key": "menuItem3Title",
"content": "First impressions"
}, {
"section": "theMobileMenu",
"key": "menuItem3Link",
"content": "/mobile/first-impressions.html"
}];

var obj = {};
var menu = data.map(function(v, k) {
if (v.key.match(/menuItem\d*Title/) !== null) {
obj = {
title: v.content
};
} else if (v.key.match(/menuItem\d*Link/) !== null) {
obj.link = v.content;
return obj;
}
});
menu = $.grep(menu, function(n) {
return n == 0 || n
});

仅当 key 的顺序与OP中所示的完全相同时,该代码才有效。

关于javascript - 从现有对象创建新的数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34368573/

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