gpt4 book ai didi

JavaScript:使用动态键值解析 JSON

转载 作者:行者123 更新时间:2023-12-01 01:52:07 24 4
gpt4 key购买 nike

我有一个如下所示的 JSON,我想从中提取列和行数组中的数据。

{
"id":0,
"tabName":"newtab",
"columns":[
{
"id":0,
"name":"firstname",
"type":"entity",
"operator":"=",
"$$hashKey":"object:40"
},
{
"id":1,
"name":"address",
"type":"domain",
"operator":"<",
"$$hashKey":"object:50"
}
],
"rows":[
{
"0":"Adam", //this first row data corresponds to "Name" column
"1":"5432 River Drive", //this first row data corresponds to "Address" column
"$$hashKey":"object:34",
"tabId":"1122",
"description":"New Tab",
"id":1
},
{
"0":"Silver", //this 2nd row data corresponds to "Name" column
"1":"Address 2", //this 2nd row data corresponds to "Address" column
"$$hashKey":"object:53",
"tabId":"2345",
"description":"New 2nd Tab",
"id":2
}
],
"uniqueIdCounter":3
}

从上面的 JSON 中,我想提取列和行值。这只是示例 JSON,实际的 JSON 可以有更多的列和行条目。

在列数组中:每个列条目的 id、名称、类型操作键保持相同。

在行数组中:每个行条目的 tabid、描述和 id 键保持相同。

行数组的问题是键值“0”、“1”(实际上对应于列名字和地址)。如何循环遍历这个数组并提取这些动态值?所谓动态,是指如果我有超过 2 行,则行中的键将为“0”、“1”、“2”,对于其他行,依此类推。

我开始编写这个循环:

var jsonColumns = JSON.parse(JSON.stringify($scope.myTable.columns));
for (var i = 0; i < jsonColumns.length; i++) {
var obj = jsonColumns[i];
//For columns data I can do obj.id, obj.name etc and works fine
}

对于行,我不确定如何继续:

var jsonRows = JSON.parse(JSON.stringify($scope.myTable.rows));
for (var i = 0; i < jsonRows.length; i++) {
var obj = jsonRows[i];
//How can I extract rows with keys "0", "1" where I dont know these key names in advance
}

请问对此有何意见?谢谢

最佳答案

假设 tabid、description、id 和 $$hashKey 是静态的,您可以按如下方式提取这些动态键,

let tableObj = {
"id":0,
"tabName":"newtab",
"columns":[
{
"id":0,
"name":"firstname",
"type":"entity",
"operator":"=",
"$$hashKey":"object:40"
},
{
"id":1,
"name":"address",
"type":"domain",
"operator":"<",
"$$hashKey":"object:50"
}
],
"rows":[
{
"0":"Adam", //this first row data corresponds to "Name" column
"1":"5432 River Drive", //this first row data corresponds to "Address" column
"$$hashKey":"object:34",
"tabId":"1122",
"description":"New Tab",
"id":1
},
{
"0":"Silver", //this 2nd row data corresponds to "Name" column
"1":"Address 2", //this 2nd row data corresponds to "Address" column
"$$hashKey":"object:53",
"tabId":"2345",
"description":"New 2nd Tab",
"id":2
}
],
"uniqueIdCounter":3
};

let jsonRows = JSON.parse(JSON.stringify(tableObj.rows));
let staticAttributes = ['tabId', 'description', 'id', '$$hashKey'];
let extractedData = [];
for (const obj of jsonRows) {
let extractedObj = {};

for (let key in obj) {
if (obj.hasOwnProperty(key) && !staticAttributes.includes(key)) {
extractedObj[key] = obj[key];
}
}

extractedData.push(extractedObj);
}

console.log(extractedData);

关于JavaScript:使用动态键值解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51393091/

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