gpt4 book ai didi

javascript - 重建 Json 列表

转载 作者:行者123 更新时间:2023-12-03 10:31:25 26 4
gpt4 key购买 nike

// Start with this JSON
var initialJson = {
"rows": [{
"ID": 123,
"Data": 430910,
"VersionNum": 0,
"RowSeqNum": 1,
"IterationNum": 1,
"FirstName": "Aqwemara",
"LastName": "Seweqweebi",
"Location": "CweAN",
"Role": "Site",
"In_Out": "Internal",
"Editor": "User1",
"Edit_Date": "2015%2D02%2D25T15%3A30%3A47%2E883Z"
}]
};


//Create an array that lists the Keys for the NEW JSON
var hResponse = [];
hResponse.push("FirstName", "LastName", "Location", "Role", "Editor", "Edit_Date");
var wbuResponse = [];

// When GO! button is pressed, process the "initialJson" object, creating a new object with only the Keys listed in "hResponse" array
$(document).ready(function() {
$('.btn').click(function() {

wbuResponse.push(
for each(hHeading in hResponse[{
hHeading: response[i].hHeading
}]);

console.log(JSON.stringify(wbuResponse));
});
});












//console setup
var consoleLine = "<p class=\"console-line\"></p>";

console = {
log: function(text) {
$("#console-log").append($(consoleLine).html(text));
}
};
.console-line {
font-family: console;
margin: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="btn" type="button" id="btn" value="Go!">
<div id="console-log"></div>

我想要获取 initialJson ,我将修改这些对,然后根据 hResponse 数组中的条目重建 JSON。

重点关注重建部分,我只想获取一定数量的 key 并将它们放入新的 JSON 数组中。

我可以在 wbuResponse.push 中为每个循环执行一次以创建正确的结构吗?我这样做对吗,也许有更好更有效的方法?

谢谢

JSFIDDLE:https://jsfiddle.net/b5m0nk67/5/

最佳答案

您要查找的内容称为 map 。它是现代 JavaScript 实现中的内置函数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

使用.map(),您的过滤代码可能如下所示:

var wbuResponse = initalJson.map(function(row, index) {
return {
FirstName: row.FirstName,
LastName: row.LastName,
Location: row.Location,
Role: row.Role,
Editor: row.Editor,
Edit_Date: row.Edit_Date
};
});

如果您想使用像您提到的那样的方法,通过一系列属性名称进行过滤而不是对其进行硬编码,您可以执行以下操作:

var props = ["FirstName", "LastName", "Location", "Role", "Editor", "Edit_Date"];

var wbuResponse = initalJson.map(function(row, index) {
var mappedRow = { };

for (var i = 0; i < props.length; i++) {
mappedRow[props[i]] = row[props[i]];
}

return mappedRow;
});

为了获得更广泛的浏览器支持,您可以使用 jQuery 的内置 map 功能,其中包括适用于本身不支持它的浏览器的填充函数。这里有几个例子:http://encosia.com/use-jquery-to-extract-data-from-html-lists-and-tables/

关于javascript - 重建 Json 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29199909/

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