xpark xpark - 2 months ago 4
JSON Question

Output value from Json Array

I'm getting output:[{"ref":"contact.html","score":0.7071067811865475}]

$.getJSON( "index.json", function(content) {
idx = lunr.Index.load(content);
var results = idx.search(variabletosearch);
var final = JSON.stringify(results);
console.log(final);
});


How can I print value of ref? Cause when I
console.log(final[0].ref);
I get undefined,?
Thanks!

Answer

EDIT:

JSON.stringify returns a string, not an object. So in this case 'final' is a string that contains the same data that was in the object 'results'

To access the data from an object, you can use result[0].ref, or if you want to use 'final' (although you don't need to), you can do this:

final = JSON.parse(final)
console.log(final[0].ref)

If it's only one object within the array, then the other answers are enough, but since arrays are used to store multiple objects, you can do this as follows:

var arr = [
    {"ref": "object1", "score": "1"},
    {"ref": "object2", "score": "2"}
]

arr.map(function(object) {
    console.log(object.ref)
})

JSFiddle using an alert instead of console.log()

You can also use a loop, but this cleaner.

Comments