Extracting data from JSON array

The output I am receiving is:

[{"ref":"contact.html","score":0.7071067811865475}]

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

How can I extract the value of 'ref'? When I attempt

console.log(formattedResults[0].ref);
it returns undefined.

Answer №1

UPDATE:

Just a reminder that JSON.stringify returns a string, not an object. Therefore, in this scenario, 'final' holds a string that mirrors the data from the 'results' object.

To retrieve data from an object, you can utilize result[0].ref. Alternatively, if you prefer to use 'final' (even though it's not necessary), you can perform the following:

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

If there is a single object in the array, the previous solutions suffice. However, since arrays are designed to accommodate multiple objects, consider the following approach:

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

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

JSFiddle showcasing the use of an alert instead of console.log()

You can also opt for a loop, although the map function provides a neater solution.

Answer №2

const data = [{"page":"home.html","rating":0.7071067811865475}];

data[0].page;

data[0] refers to the first element in the array, which is the object

{"page":"home.html","rating":0.7071067811865475}
. You can access the properties of the object using dot notation.

Here is an expanded version:

const data = [{"page":"home.html","rating":0.7071067811865475}];
const myItem = data[0];
console.log(myItem.page);
// you could also include null checks
if (myItem) {
  console.log(myItem.page ? myItem.page : 'no entry');
}

Answer №3

Let's say

let example = [{"location":"page.html","value":0.7071067811865475}];

therefore:

let location = example[0].location;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show the JSON data retrieved from an AJAX request in an HTML table

After receiving the JSON response below from an AJAX call: {"items":[{"name":"MP 201SPF_1C","productNo":"123","commerceItemQty":1,"price":"$350.00","leaseOrNot":"false"},{"name":"MP 201SPF_1C","productNo":"456","commerceItemQty":4,"price":"$1,400.00","lea ...

Tips on decoding the JSON response provided below

After making an ajax call, I am receiving the following JSON response: {"head":{"json":"{ 'rows': [ {'CustName' : 'JAMES', 'CustId' : 'Gans Communications'} , {'CustName' : 'JAMES', &ap ...

Exploring the World of Three.js Loaders

I downloaded the file package three.js-dev from threejs.org and I am trying to use it in my project like this: <script type="text/javascript" src="./build/three.js"></script> <script type="text/javascript" src="./src/loaders/JSONLoader.js" ...

filter supabase to only show items with numbers greater than or equal to a

Hey there! Currently, I am in the process of setting up a store using nextjs pages router and supabase. However, I have encountered a peculiar bug with my product filtering system when dealing with numbers exceeding 4 digits (e.g., 11000). The structure o ...

Unlock the secret to retrieving specific properties from a JSON object

Whenever this code is executed: import requests import json def obtain_sole_fact(): catFact = requests.get("https://catfact.ninja/fact?max_length=140") json_data = json.loads(catFact.text) return json_data['fact'] print(obtain_s ...

Customize AngularJS checkbox values when checked

Is there a way to set a checkbox to be checked by default with a custom value instead of a boolean value? Ready to go? <input type="checkbox" ng-model="checked" ng-init="checked=true" ng-true-value="sure" ng-false-value="nope"><br/> <tt> ...

Implementing Express.js allows for the seamless casting of interfaces by the body within the request

I have created a similar structure to ASP.NET MVC and uploaded it on my github repository (express-mvc). Everything seems fine, but I am facing an issue with casting the body inside the request object to match any interface. This is what I am aiming for: ...

Determine the 'source' attribute value of the image (img) with a dynamically changing Id

Below is the code snippet: <img id="simple_captcha-ad089ff4819" src="/simple_captcha?code=a35401d"> The id of the above img tag changes constantly with each new action. For example, the next id could be "simple_captcha-sfw454sdfs". Therefore, I n ...

Emit data asynchronously upon returning

In my node.js application, I have a background process implemented using the EventEmitter. Here is a snippet of how it is used: var event = { returnValue: undefined }; eventEmitter.emit('name', event, argument); return event.returnValue; // This ...

The onBlur event attached to a div is triggered when transitioning from one input element to another within the same div

Here's a scenario: I have a div with two input fields nested inside, like this: <div> <input placeholder="Input1"/> <input placeholder="Input2"/> </div> I have a requirement to trigger a specific ...

Guide on updating a single element in a Firebase array

I have an array stored in my firebase database, structured like this: matches:[ {match:{id:1,data:...}}] I am looking for a way to update just one specific item within this array. Let's say I want to locate the match with the ID of 32 and modify its ...

What steps can I take to make sure JSON keys containing only digits are treated as Strings instead of Numbers?

Within a JSON String, I have IDs as keys, represented as Strings of numbers, while the values are actual Numbers (Float). The problem arises when parsing this information to obtain an object in Safari 10.1.2... var jsonData = "{\"53352\":0.6, ...

Free up MySQL connections within a Promise.All implementation

At the moment, I am facing issues with releasing MySQL connections from a connection pool. Interestingly, when I release connections in a synchronous "for" loop, everything works fine. However, when I attempt to release them asynchronously using Promise.Al ...

Troubleshooting Issue with Formidable Not Working with Multer

Attempting to develop a webpage that enables users to upload a file to a designated folder while specifying a number in an input field. Currently, I am navigating through the Multer library despite typically using body-parser. Referencing both my app.js an ...

I am unable to integrate Autoprefixer into an Express project

I am having trouble adding Autoprefixers to the postcssmiddleware, as mentioned in the documentation here I also attempted using express-autoprefixers but still cannot see the vendors in my dest or public folder. You can find a link to my repository (node ...

Leveraging a standard JSON Object for Request Body

In my current setup, the controller I am working with is designed to accept a JSON Object as input. The challenge I am facing is that the structure of the JSON varies with each request, making it difficult to map the input to a specific POJO. Is there ...

Problems with Google Maps Event Tracker

I recently inherited a section of code that utilizes the Google Maps API to place markers on a map along with information windows. Below is an excerpt from the code responsible for creating the markers and setting up event listeners: if(markers.length > ...

Evolution of the material through a fresh new slide

Can someone assist me with an animation issue? I have a slideshow consisting of 4 images that are supposed to transition automatically after a set time interval. Upon initially loading the webpage, the animation works perfectly as intended. However, subs ...

Add the current date plus 48 hours to the content on a webpage (JavaScript maybe?)

Hello there, I am currently in the process of setting up a small online store for a farm using Squarespace. One thing I would like to implement is specifying that items will be available for pickup two days after they are purchased online, instead of imme ...

Annoying scrolling issue arising from using jQuery Buttonset

Dealing with jQuery UI buttons and buttonsets has been quite a challenge for me. Despite searching extensively on this site, I have yet to find a satisfactory solution that works smoothly. My setup includes jQuery rev 1.11.1 and jQuery UI rev 1.9.2. The i ...