[英]How do I loop through a JSON object in MarkLogic to push all the keys in an array?
I have a multi level JSON like in the example below. 我有一个多级JSON,如下面的示例所示。 I want to write a simple code to loop through it and fetch all the keys there are in it for validation purposes. 我想编写一个简单的代码来遍历它,并获取其中包含的所有密钥以用于验证。
I tried Object.keys()
but that gives the keys only for the first level of the object. 我尝试了Object.keys()
但是它仅提供对象第一级的键。 How do I loop it to get the whole result? 我如何循环以获得完整结果?
{
"id": "0001",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1004",
"type": "Devil's Food"
}
]
},
"topping": {
"id": "5001",
"type": "None",
"moreData": {
"id": "5003",
"type1": "Chocolate",
"type2": {
"id": "5004",
"type": "Maple"
}
}
}
}
I normally get only the first keys, ie "id", "ppu","batters",topping" but I want all the keys including "batter", "type", "moreData", etc. NOTE: All my keys are unique unlike the example below. 我通常只得到第一个键,即“ id”,“ ppu”,“ batters”,topping”,但我希望所有键都包括“ batter”,“ type”,“ moreData”等。 注意:我所有的键都是与下面的示例不同。
EDIT - Code that I'm trying: 编辑-我正在尝试的代码:
function keyCheck(obj) {
var a = Object.keys(obj);
var arr=[];
arr.push(a);
for (var i = 0; i < a.length; i++) {
var b = obj[a[i]];
if (typeof (b) == 'object') {
keyCheck(b);
}
}
return arr[0];
}
keyCheck(obj);
You can write a recursive method as follows, 您可以编写如下的递归方法,
let obj = { "id": "0001", "ppu": 0.55, "batters": { "batter": [{ "id": "1001", "type": "Regular" }, { "id": "1004", "type": "Devil's Food" } ] }, "topping": { "id": "5001", "type": "None", "moreData": { "id": "5003", "type1": "Chocolate", "type2": { "id": "5004", "type": "Maple" } } } } function getKeys(obj, arr = []) { Object.entries(obj).forEach(([key, value]) => { if(typeof value === 'object' && !Array.isArray(value)) { arr.push(key); getKeys(value, arr); } else { arr.push(key); } }); return arr; } console.log(getKeys(obj));
For old browsers 对于旧的浏览器
function getKeys(obj, arr = []) {
Object.entries(obj).forEach(function(entry) {
let key = entry[0];
let value = entry[1]
if(typeof value === 'object' && !Array.isArray(value)) {
arr.push(key);
getKeys(value, arr);
} else {
arr.push(key);
}
});
return arr;
}
You can achieve this with making a recursive
function with Object.keys()
您可以通过使用Object.keys()
进行recursive
函数来实现
const object = { id: '0001', ppu: 0.55, batters: { batter: [{ id: '1001', type: 'Regular', }, { id: '1004', type: "Devil's Food", }, ], }, topping: { id: '5001', type: 'None', moreData: { id: '5003', type1: 'Chocolate', type2: { id: '5004', type: 'Maple', }, }, }, }; function getKeyNames(obj, secondObj) { Object.keys(obj).forEach((r) => { const elem = obj[r]; const refObj = secondObj; if (!Array.isArray(elem)) { refObj[r] = r; } if (typeof elem === 'object' && (!Array.isArray(elem))) { getKeyNames(elem, secondObj); } }); return secondObj; } function getAllKeys(obj) { const secondObj = {}; const keys = getKeyNames(obj, secondObj); return Object.keys(keys); } const result = getAllKeys(object); console.log(result);
You can use a recursive function to get all the keys. 您可以使用递归函数来获取所有键。 Below method takes a second argument unique
that lets you set if keys should be duplicated in your resulting array of keys. 下面的方法采用了另一个unique
参数,该参数可让您设置是否应在结果键数组中重复键。
const allKeys = (obj, unique = true) => { const res = Object.entries(obj).flatMap(([k, v]) => { if (typeof v === 'object') { if (Array.isArray(v)) return [k, v.flatMap(vv => allKeys(vv, unique))].flat(); return [k, allKeys(v, unique)].flat(); } return k; }); return unique ? [...new Set(res)] : res; }; console.log(allKeys(obj));
<script> const obj = { "id": "0001", "ppu": 0.55, "batters": { "batter": [{ "id": "1001", "type": "Regular" }, { "id": "1004", "type": "Devil's Food" } ] }, "topping": { "id": "5001", "type": "None", "moreData": { "id": "5003", "type1": "Chocolate", "type2": { "id": "5004", "type": "Maple" } } } }; </script>
The JSON.parse
reviver parameter can be used to get all key value pairs : JSON.parse
reviver参数可用于获取所有键值对:
var keys = {}, json = '{"id":"0001","ppu":0.55,"batters":{"batter":[{"id":"1001","type":"Regular"},{"id":"1004","type":"Devil\\'s Food"}]},"topping":{"id":"5001","type":"None","moreData":{"id":"5003","type1":"Chocolate","type2":{"id":"5004","type":"Maple"}}}}' JSON.parse(json, function(key, value) { if ( isNaN(key) ) keys[key] = value }) console.log( Object.keys(keys) )
So I figured out a solution by using the inputs provided by everyone here.Due to some policy I cannot post my own solution but this is what I did: Get Object.keys() for first level data. 所以我通过使用这里每个人提供的输入来找到了解决方案。由于某些策略,我无法发布自己的解决方案,但这是我做的:获取Object.keys()用于第一级数据。 Check if it's another object or array & call the same function recursively. 检查它是另一个对象还是数组,并递归调用同一函数。 If not then add it to the array. 如果没有,则将其添加到阵列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.