-
温温酱
只需使用一个简单的正则表达式来匹配石钥匙,/stone_/gi方法如下:var names = { "pebble": { "status": "active" }, "stone": { "status": "active" }, "stone_ny": { "status": "active" }, "stone_london": { "status": "active" }, "stone_tokyo": { "status": "active" }}var matchedNames = {};for (name in names) { if (/stone_/gi.test(name)) { matchedNames[name] = names[name]; }}console.log(matchedNames);Explanation of regex:g = 全局,匹配字符串中模式的所有实例,而不仅仅是一个i = 不区分大小写(例如,/a/i 将匹配字符串“a”或“A”。
-
慕田峪4524236
JSON 数据本质上具有 SQL 无法做到的灵活性。这就是它变得如此普遍的原因。假设您的数据位于一个名为的变量中datavar data = { "pebble": { "status": "active" }, "stone": { "status": "active" }, "stone_ny": { "status": "active" }, "stone_london": { "status": "active" }, "stone_tokyo": { "status": "active" }}const result = Object.keys(data) .filter(key => key.match(/^stone_/) // This does the filtering (the WHERE clause) .map(key => { return {[key]: data[key]}}) // This returns your selected rows
-
萧十郎
您可以使用for...in循环遍历所有可枚举字符串属性(包括继承一次)。您可以将其与正则表达式匹配结合起来,以检查密钥是否满足您的要求。const data = { "pebble" : { "status": "active" }, "stone" : { "status": "active" }, "stone_ny" : { "status": "active" }, "stone_london": { "status": "active" }, "stone_tokyo" : { "status": "active" },};const result = {};for (const key in data) { if (key.match(/^stone_/)) result[key] = data[key];}console.log(result);但是,如果您当前已经在使用库,您可以检查是否有助手存在。一个常见的名称是pickBy()接受对象和谓词(测试函数)。在洛达什:const result = _.pickBy(data, (_, key) => key.match(/^stone_/));在拉姆达:const result = R.pickBy((_, key) => key.match(/^stone_/), data);
// or: const result = R.pickBy(R.flip(R.test(/^stone_/)), data);如果输入是对象,某些库也可能使用filter()并返回对象。
-
胡说叔叔
source={ "pebble": { "status" : "active" }, "stone": { "status" : "active" }, "stone_ny" { "status" : "active" }, "stone_london": { "status" : "active" }, "stone_tokyo": { "status" : "active" }};rows = [];for(var k in source) if(k.substr(0,6)=="stone_") rows.push({[k]:source[k]});
-
墨色风雨
var data = { "pebble": { "status": "active" }, "stone": { "status": "active" }, "stone_ny": { "status": "active" }, "stone_london": { "status": "active" }, "stone_tokyo": { "status": "active" }}const query = Object.entries(data).reduce((acc, val)=> { return val[0].slice(0, 6) === 'stone_' ? {...acc, [val[0]]: val[1]} : acc}, {})