// 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。
专注于重建部分,我只想获取一定数量的密钥并将它们放入新的JSON数组中。
我可以为wbuResponse.push
中的每个循环创建一个正确的结构吗?
我这样做是对的吗,也许有更好的更有效的方式?
由于
JSFIDDLE:https://jsfiddle.net/b5m0nk67/5/
答案 0 :(得分:1)
您正在寻找的是地图。它是现代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的内置地图功能,其中包含一个不支持本机支持的浏览器的polyfill。这里有一些例子:http://encosia.com/use-jquery-to-extract-data-from-html-lists-and-tables/