Javascript:在 JSON 中查找键及其值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42492555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:11:39  来源:igfitidea点击:

Javascript: Find key and its value in JSON

javascriptjson

提问by AmazingDayToday

I have a JSON object that is returned in different ways, but always has key. How can I get it?

我有一个以不同方式返回的 JSON 对象,但总是有key. 我怎么才能得到它?

E.g.

例如

"Records": {
    "key": "112"
}

Or

或者

"Records": { 
    "test": {
        "key": "512"
    }
}

Or even in array:

甚至在数组中:

"Records": { 
    "test": {
        "test2": [
            {
                "key": "334"
            }
        ]
    }
}

Tried several options, but still can't figure out (

尝试了几个选项,但仍然无法弄清楚(

采纳答案by Shobhit Walia

I will not write the code for you but give you an idea may be it will help, First convert JSON object in to string using

我不会为您编写代码,但给您一个想法可能会有所帮助,首先使用将 JSON 对象转换为字符串

JSON.stringify(obj);

after that search for Key using indexOf() method. Extract previous '{' and Next '}' string and again cast in to JSON object. using

在使用 indexOf() 方法搜索 Key 之后。提取上一个 '{' 和下一个 '}' 字符串并再次转换为 JSON 对象。使用

var obj =  JSON.parse(string);

Then

然后

 var value = obj.key

回答by Maciej Kozieja

I think this migth be solution (asuming key is always string and you don't care about res of data)

我认为这可能是解决方案(假设键始终是字符串并且您不关心数据的 res )

const data = [`"Records": { 
    "test": {
        "test2": [
            {
                "key": "334",
    "key": "3343"
            }
        ]
    }
}`, `"Records": { 
    "test": {
        "key": "512"
    }
}`, `"Records": {
    "key": "112"
}`]

const getKeys = data => {
  const keys = []
  const regex = /"key"\s*:\s*"(.*)"/g
  let temp
  while(temp = regex.exec(data)){
    keys.push(temp[1])
  }
  return keys
}

for(let json of data){
  console.log(getKeys(json))
}

回答by Грозный

How can i get it?

我怎么才能得到它?

Recursively! e.g.

递归!例如

function getKey(rec) {
    if (rec.key) return rec.key;

    return getKey(rec[Object.keys(rec)[0]]);
}

https://jsfiddle.net/su42h2et/

https://jsfiddle.net/su42h2et/

回答by Nina Scholz

You could use an iterative and recursive approach for getting the object with keyin it.

您可以使用迭代和递归方法来获取其中的对象key

function getKeyReference(object) {
    function f(o) {
        if (!o || typeof o !== 'object') {
            return;
        }
        if ('key' in o) {
            reference = o;
            return true;
        }
        Object.keys(o).some(function (k) {
            return f(o[k]);
        });
    }

    var reference;
    f(object);
    return reference;
}

var o1 = { Records: { key: "112" } },
    o2 = { Records: { test: { key: "512" } } },
    o3 = { Records: { test: { test2: [{ key: "334" }] } } };

console.log(getKeyReference(o1));
console.log(getKeyReference(o2));
console.log(getKeyReference(o3));

回答by Tan

You can try this

你可以试试这个

const data = {
 "Records": {
  "key": "112"
 }
};

const data2 = {
 "Records": {
  "test": { "key": "512" }
 }
};

const data3 = {
 "Records": {
  "test": {
   "test2": [
    { "key": "334" },
   ]
  }
 }
};

function searchKey(obj, key = 'key') {
 return Object.keys(obj).reduce((finalObj, objKey) => {
  if (objKey !== key) {
   return searchKey(obj[objKey]);
  } else {
   return finalObj = obj[objKey];
  }

 }, [])
}

const result = searchKey(data);
const result2 = searchKey(data2);
const result3 = searchKey(data3);
console.log(result);
console.log(result2);
console.log(result3);