简体   繁体   中英

How to perform wildcard key search in JSON using Javascript?

How to perform key search in JSON? I want to get all matching string keys from the JSON, not the values.

 let json = { "first": { "first_fullname": 'abc', "first_address": '1 street name', "first_phone": 123456 }, "second": { "second_fullname": 'xyz', "second_address": '2 street name', "second_phone": 987654 } } var prop1 = 'first_address' var prop2 = 'address' Object.keys(json).forEach((person) => { Object.keys(json[person]).forEach((attr) => { if (prop1 in json[person]) { console.log(prop1) } }) }); Object.keys(json).forEach((person) => { Object.keys(json[person]).forEach((attr) => { if (prop2 in json[person]) { console.log(prop2) } }) });

Expecting all key strings containing *address* , with use of wildcard.

first_address
second_address

I would write this as a function which takes the property and a wildcard flag, and then filter the keys of each person to find ones which match the property, using strict equality for no wildcard or String.includes for wildcards:

 let json = { "first": { "first_fullname": 'abc', "first_address": '1 street name', "first_phone": 123456 }, "second": { "second_fullname": 'xyz', "second_address": '2 street name', "second_phone": 987654 } } var prop1 = 'first_address' var prop2 = 'address' const hasProp = (json, prop, wildcard) => Object.values(json).flatMap(person => Object.keys(person).filter(key => wildcard? key.includes(prop): key === prop) ) console.log(hasProp(json, prop1, false)) console.log(hasProp(json, prop2, true))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM