Discovering a specific value within a JSON stringified array

I am looking for a specific value within a JSON stringify array

[{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:52:02"},{"id":"435","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:55:26"},{"id":"436","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:58:50"},{"id":"437","temperature":"22.00","humidity":"48","createat":"2015-10-11 20:02:14"},{"id":"438","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:23:15"},{"id":"439","temperature":"22.50","humidity":"50","createat":"2015-10-11 21:24:37"},{"id":"440","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:17"},{"id":"441","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:41"}]

My approach is to check whether the value I am adding is not already present in the array

Answer №1

// Transform JSON data into a string
jsonString = '[{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:52:02"},{"id":"435","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:55:26"},{"id":"436","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:58:50"},{"id":"437","temperature":"22.00","humidity":"48","createat":"2015-10-11 20:02:14"},{"id":"438","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:23:15"},{"id":"439","temperature":"22.50","humidity":"50","createat":"2015-10-11 21:24:37"},{"id":"440","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:17"},{"id":"441","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:41"}]';

// Convert the stringified JSON to a JavaScript object
parsedData = JSON.parse(jsonString);

// Define the index of the object you wish to verify
index = 0;

// Check if the specified property exists
if (typeof parsedData[index].humidity !== 'undefined') {
  // Assign the property if it exists
  parsedData.humidity = 1;
}

// Convert the object back to a string
jsonString = JSON.stringify(parsedData);

UPDATE: Below is a function named propertyExists:

var propertyExists = function(jsonString, id, property) {
  // Parse the JSON string into a JavaScript object
  parsedData = JSON.parse(jsonString);
  // Check if the property exists for the given ID
  for (var i = 0; i < parsedData.length; i += 1) {
    if (parseInt(parsedData[i].id) === parseInt(id)) {
      return (typeof parsedData[i][property] !== 'undefined');
    }
  }
  return false;
}

// JSON data in string format
var jsonString = '[{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:52:02"},{"id":"435","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:55:26"},{"id":"436","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:58:50"},{"id":"437","temperature":"22.00","humidity":"48","createat":"2015-10-11 20:02:14"},{"id":"438","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:23:15"},{"id":"439","temperature":"22.50","humidity":"50","createat":"2015-10-11 21:24:37"},{"id":"440","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:17"},{"id":"441","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:41"}]';

console.log(propertyExists(jsonString, 432, 'humidity'));

Answer №2

....

const dataObj = [{"id":"543","temperature":"2","humidity":"3",.....

let isFound = false;
dataObj.forEach((index,value) => {
    if(dataObj[index].id === newRecord.id){
        isFound = true;
    }
});
if(!isFound){
    dataObj.push(newRecord);
}

....

Answer №3

I am searching for a specific value within a JSON stringify array.

If you want to check if the array contains an object with a certain property that has a specific value, you can use the Array.prototype.some method like this:

function hasPropValue(array, prop, value) {
  return array.some(function(obj) {
    return obj.hasOwnProperty(prop) && obj[prop] === value;
  });
}

some will stop iterating once it finds a match. If your data is in valid JSON format, you can parse it and use the function like this:

hasPropValue(JSON.parse(jsonText), 'id', '432');

var jsonText = '[{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:52:02"},{"id":"435","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:55:26"},{"id":"436","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:58:50"},{"id":"437","temperature":"22.00","humidity":"48","createat":"2015-10-11 20:02:14"},{"id":"438","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:23:15"},{"id":"439","temperature":"22.50","humidity":"50","createat":"2015-10-11 21:24:37"},{"id":"440","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:17"},{"id":"441","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:41"}]'

function hasPropValue(array, prop, value) {
  return array.some(function(obj) {
    return obj.hasOwnProperty(prop) && obj[prop] === value;
  });
}

document.write(hasPropValue(JSON.parse(jsonText), 'id', '432'));

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

Setting up a Node.js application with Nginx on DigitalOcean

While running my application on a DigitalOcean droplet using nginx, I encountered a peculiar issue. The app runs perfectly fine with http, but when switching to https, nginx throws a 502 BAD GATEWAY error. Despite trying various DigitalOcean guides and sco ...

Using Vue3 to create a dynamic reference in a computed status, allowing for the repetition of a player multiple times in a table along with a play/pause

On the Vue3 page below, I have successfully integrated a player that displays a "play" icon when the player is stopped and a "pause" icon when it's playing. Now, my goal is to allow the player to repeat n times by placing it in a table. The challeng ...

Mongoose - facing issues with $and operator, looking for a way to locate an array containing both items

I'm currently developing a chat-based application that involves private messaging between individuals. Essentially, a Chat model in my application consists of the following schema: let schema = new Schema({ members: [{ type: ObjectId, ref: models.u ...

What is the best method for passing information to my frontend JavaScript files using Express?

When using ejs to render my html pages, I pass in data in the following manner: collection.find({}).toArray( function (err, results) { res.render('index', { results: results, ...

Having trouble accessing a specific array index in a JSON response from the Quandl API using Google Apps Script because it's showing as "undefined"

My experience with JSON is limited, mainly using Linux command line tools in Python. I am currently working on a project with Google Apps Scripts where I need to retrieve specific data from the Quandl API. In this case, I am interested in extracting the "C ...

Invoking controller from a view using a JavaScript function in CakePHP 1.3

I am working with a map in Javascript and I need to select a rectangular zone on my Google Map without clicking anywhere. Once I have the two corner coordinates, I want to send them to my CakePHP Controller. Can anyone help me figure out how to do this? H ...

I am facing issues with jQuery's live and livequery functions when trying to use them with a form that is being loaded dynamically through

Previously, I inquired about a related issue regarding attaching behavior to an element with jQuery after insertion. However, I have not yet found a solution. For clarity's sake, I am posing a new question with a different scenario. Below is the code ...

The error message "AttributeError: module 'pandas' does not have the attribute 'DataFrame'" indicates that the code is correct

Just ran this code snippet for testing import pandas as pd userInput ={ 'Principal':1000, 'terms':15, 'age':33, 'Gender':1, 'weekend':1, 'Bechalor':0, 'High Sch ...

I am having difficulty converting a Json file into a java object using Gson

My Json file contains information about an airport: { "airports": [ { "fs": "VGO", "iata": "VGO", "icao": "LEVX", "name": "Vigo Airport", "city": "Vigo", "cityCode": "VGO", "stateCode": "SP", "countryCode": "ES", "countryName ...

transferring information from browser storage to the server

On my web app, there is a feature that saves data to local storage and converts it to a JSON object. I'm interested in passing this local storage data to my server using AJAX, so that other clients of the web app can access it. Is there a way to accom ...

What is the best way to read a file or Stream synchronously in node.js?

Kindly refrain from lecturing me on asynchronous methods. Sometimes, I prefer to do things the straightforward way so I can swiftly move on to other tasks. Unfortunately, the code below is not functioning as expected. It closely resembles code that was po ...

Yeoman Error: Issue with 'mkdir' in Javascript Execution

Currently, I am in the process of setting up a Meanjs instance using a Yeoman generator. However, when I execute 'sudo yo meanjs', everything goes smoothly until an issue arises while attempting to create a directory and it fails. Any insights on ...

Imposing the situation

In my current class, I have a private property and a public method for access: Person = function () { this.Name = "asd"; var _public = new Object(); _public.Name = function (value) { if (value == undefined) { //Get return ...

Updating the content of a window without the need to refresh the page using JavaScript

Is there a way to navigate back to the previous window in chat_user without refreshing the entire page when the back button is clicked? Below is the code I have tried: <a href="" onclick="window.history.go(-1); return false;">back</a> ...

Is there a way to make my code on Google Sheets work across multiple tabs?

My Google Sheets code successfully pulls information from the main tab into my CRM Software every time someone fills out a form online. However, I'm struggling to get the script to run for multiple tabs on the same spreadsheet. I've tried a few s ...

Display picture on webpage in 10 seconds

Hi, I'm working on a website project and I've run into an issue where I need to use JavaScript, but I haven't mastered it yet. I have a background image slideshow set up where a new image appears every 6 seconds. My idea is to have the sec ...

I am facing an issue where both curl and file_get_contents are not functioning properly after

When attempting to access a user's city information using coordinates, I have encountered an issue with the response not being displayed in my console. The process involves a javascript function that takes latitude and longitude data, sends it to a PH ...

Obtaining JSON data in React Native without prior knowledge of the key

When I receive this type of data, the keys are common but the items vary. How can I extract and add this data to my list of categories? { "99": "Venues", "100": "Party Supplies", "101": "Enter ...

Compare the versions of React used in the linked library and the workspace application

As I work on developing a React library containing my commonly used components, I have organized my project structure in the following way: In the root folder, there is my rollup config file and the src/ folder which houses my library. Upon building, the ...

Using the FileInput Shiny App to Upload JSON Files

I'm currently working on developing a shiny app that can load and display data from a .json file in a table format. I've attempted to import the data and present it using DataTable along with the fromJson function from Json Lite. options(shiny ...