0

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? When I console.log(final[0].ref); I get undefined.

tcooc
  • 20,629
  • 3
  • 39
  • 57
xpark
  • 51
  • 1
  • 11
  • 2
    Possible duplicate of [Access / process (nested) objects, arrays or JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json) – Teemu Sep 22 '16 at 15:30
  • `final` is a string (the output of `JSON.stringify`)... you probably want to `console.log(results[0].ref);` – pherris Sep 22 '16 at 17:02

3 Answers3

1
var a = [{"ref":"contact.html","score":0.7071067811865475}];

a[0].ref;

a[0] is the '0'th (or first) element in the array which is the object literal {"ref":"contact.html","score":0.7071067811865475} from here you can access the object normally using dot notation.

Expanded out a bit:

var a = [{"ref":"contact.html","score":0.7071067811865475}];
var myObject = a[0];
console.log(myObject.ref);
//or with null checking
if (myObject) {
  console.log(myObject.ref ? myObject.ref : 'no value');
}
pherris
  • 17,195
  • 8
  • 42
  • 58
  • I don't have the variable ready, actually I get it through lunr(lunrjs.com) $.getJSON( "index.json", function(content) { searchterm = "randomstring"; idx = lunr.Index.load(content); var results = idx.search(searchterm); var final = JSON.stringify(results); console.log(final[0].ref); }); But I get undefined. But when I console.log(final), i get [{"ref":"contact.html","score":0.7071067811865475}] – xpark Sep 22 '16 at 15:52
1

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.

Omar A
  • 435
  • 7
  • 14
0

Well, assuming

var myvar = [{"ref":"contact.html","score":0.7071067811865475}];

then:

var myref = myvar[0].ref;
abidibo
  • 4,175
  • 2
  • 25
  • 33