I have this object value
var data = {
"questions": {
"0": {
"0": "17",
"1": "12"
},
"1": {
"0": "22",
"1": "34"
},
"2": {
"0": "52",
"1": "61"
}
}
}
I am trying to get value from these objects as I have tried below things which return me other than what I actually want.
alert(Object.keys(data.questions[0])); // Output : 0,1
alert(Object.keys(data.questions[0][0])); // Output : 0
alert(Object.keys(data.questions[0][1])); // Output : 0
Anyone can help me find the value of above keys like:
questions[0][0] = 17
questions[0][1] = 12
You get the result without Object.keys
.
var data = { questions: { 0: { 0: "17", 1: "12" }, 1: { 0: "22", 1: "34" }, 2: { 0: "52", 1: "61" } } }; console.log(data.questions[0]); // { 0: "17", 1: "12" } console.log(data.questions[0][0]); // 17 console.log(data.questions[0][1]); // 12
For searching a value's path of keys, you could use an iterative and recursive approach by checking all keys and objects.
function findValue(object, value) { var p; Object.keys(object).some(function (k) { var t; if (object[k] === value) { p = [k]; return true; } if (object[k] && typeof object[k] === 'object' && (t = findValue(object[k], value))) { p = [k].concat(t); return true; } }); return p; } var data = { questions: { 0: { 0: "17", 1: "12" }, 1: { 0: "22", 1: "34" }, 2: { 0: "52", 1: "61" } } }; console.log(findValue(data, '17')); console.log(findValue(data, '34'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
To get length of any particular question (in your data structure) use
Object.keys(data.questions["0"])
or Object.keys(data.questions["1"])
to get value of any questions use
data.questions["0"]["0"]
or data.questions["0"]["1"]
or data.questions["1"]["0"]
and so on..
Try like this.
var data = { "questions": { "0": { "0": "17", "1": "12" }, "1": { "0": "22", "1": "34" }, "2": { "0": "52", "1": "61" } } } console.log(data.questions["0"]); console.log(data.questions["0"]["0"]); console.log(data.questions["0"]["1"]);
Can you change the data structure? If I were you I would change it to the following:
var data = { "questions": [ [17, 22], [22, 34], [52, 61] ] }; console.log(data.questions[0]); // Output : 17,22 console.log(data.questions[0][0]); // Output : 17 console.log(data.questions[1][1]); // Output : 34
To access the first object ["0"]
To access the first two object : ["0"]["0"]
and so on based on the above expression we can access the objects like this
var data = { "questions": { "0": { "0": "17", "1": "12" }, "1": { "0": "22", "1": "34" }, "2": { "0": "52", "1": "61" } } } console.log(data.questions["0"]); console.log(data.questions["0"]["0"]); console.log(data.questions["0"]["1"]); console.log(data.questions["1"]["1"]);
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.