Retrieve the value of an object from a string and make a comparison

var siteList = {};
var siteInfo = [];
var part_str = '[{"part":"00000PD","partSupplier":"DELL"}]';
var part =  part_str.substring(1,part_str.length-1);

eval('var partobj='+part );
console.log(partobj.part);
console.log(partobj.partSupplier);

The code above is functioning properly. My task now is to compare the part number with a specific value. If they do not match, the partSupplier will be added to the JSON data; otherwise, it won't.

if (partobj.part.includes("00000PD")){
  var partSupp= partobj.partSupplier;
} else {
  partSupp= "HP";
}

siteInfo = {
  "Parts_Num": part,
  "partSupplier": partSupp
}
siteList.siteInfo.push(siteInfo);

I attempted the following approach, but the partSupplier field remains empty:

if (partobj.part.includes("00000PD")){
  var  partSupp = [partobj.partSupplier];
  console.log('partSupp' || partSupp);
} else {
  partSupp = "HP";
}

The output from the console:

partSupp
No value is being returned.

I am utilizing console.log for testing purposes before finalizing the code.

Answer №1

To extract an array from a string, utilize JSON.parse, followed by using Array#find to locate the object containing the desired part.

const partData = '[{"part":"00000PD","partSupplier":"DELL"}]';
const dataArray = JSON.parse(partData);
const foundObject = dataArray.find(item => item.part.includes("00000PD"));
if (foundObject) {
  console.log(foundObject.partSupplier);
}

Answer №2

This code snippet introduces some modifications to your original queries.

The key part is around line 7, where the value of part_str is transformed into a JSON array and then the first item (presumably the desired action) is selected.

It then checks if the string in partObj.part contains a specific value to determine the partSupplier, otherwise it defaults to "HP".

Finally, the script uses this information to construct a new object called siteInfo before appending it to the existing siteList object.

var siteList = {
  siteInfo: []
};
var part_str = '[{"part":"00000PD","partSupplier":"DELL"}]';

const partArr = JSON.parse(part_str);

var partObj = partArr[0];
var partSupp = partObj?.part?.includes("00000PD") ? partObj.partSupplier : "HP";

siteInfo = {
  "Parts_Num": part,
  "partSupplier": partSupp
}
siteList.siteInfo.push(siteInfo);

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

What is the best way to combine duplicate JSON objects together?

I am facing a challenge with my json data structure, shown below: [{ "attributeId": 6, "attributeType": "price", "attributeValue": "{10,20,100}", "displayOn": "true", "attributeName": "price" }, { "attributeId": 6, "attribu ...

Steps to link a specific section of a Google pie chart:

I have a question that may be a little confusing, so let me explain. I recently used Google Charts to create a simple pie chart and it worked perfectly. Now, I am trying to figure out how to link each section/part of the pie chart to display a jQuery moda ...

Transforming JSON object to an array of arrays using JavaScript

Attempting to extract specific values from a JSON object and store them in an array can be quite tricky. Below is an example of what this process might look like: Example: var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]}, "2 ...

Sequelize is unable to retrieve a table from the database

I am configuring Sequelize in order to streamline the manipulation of an MSSQL database. My attempt to define a table called 'Stock' has resulted in unexpected behavior when trying to query it. Below is the code snippet I used for defining the t ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

One way to determine whether .ajax is using Get or POST is to check the type parameter

I have a query: $.ajax({ url: "http://twitter.com/status/user_timeline/treason.json?count=10&callback=?", success: function (data, textStatus, jqXHR) { }, error: function (jqXHR, textStatus, errorThrown ...

Error: Unable to access attributes of null object (specifically 'disable click')

Currently, I am integrating react-leaflet with nextjs. Within the markers, there are popups containing buttons that open another page upon click. However, I have encountered an error when navigating to the new page: Unhandled Runtime Error TypeError: Canno ...

Jackson: Deserialize a JSON object (missing some fields) into a Plain Old Java Object (POJO)

Recently, I encountered a JSON entry that looked like this: { "name" : "tom" "age" : 10 } Interestingly, some JSON entries also contain an additional field called address. In order to properly read this data into a P ...

What is the best way to retrieve certain items from an array that has been converted into table rows using React?

I'm currently using React.js to develop a feature on our website that displays a list of names. Each person's information is stored as objects within an array. With the help of the .map function, I was able to successfully generate the list in ta ...

Designing a slider to display a collection of images

I am currently working on a slider project using HTML, javascript, and CSS. I'm facing an issue where only the first two images (li) are being displayed and it's not transitioning to the other (li) elements. Below is the HTML code snippet: <se ...

Passing resolved data from a parent state to a nested view in Angular UI Router

Currently, I am developing an Angular web application that will showcase various financial events for the user. These events are categorized under a single ID and grouped into different categories. Each group needs to have its own HTML <table> for di ...

Is there an equivalent of getElementById for placeholder text?

I need help automating the input of information on a webpage using JavaScript. Each field has a unique ID, like this: <div id="cc-container" class="field has-float-label"> <input placeholder="ccnumber" id="credit_card_number" maxlength="16" ...

What is preventing me from loading js and css files on my web pages?

I have developed a web application using SpringMVC with Thymeleaf and I am encountering an issue while trying to load javascript and CSS on my HTML5 pages. Here is a snippet from my login.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head&g ...

Why am I unable to attach this to JQuery?

$("input").keydown(function(event){ if(event.keyCode === 13){ return false; } }); I need to prevent the default action when the "enter" key is pressed in any of my text input fie ...

JavaScript stylesheet library

What is the top choice for an open-source JavaScript CSS framework to use? ...

Is there a way to append a URL parameter after a link is clicked using Vue.js?

I am currently working on integrating heading links on my website's sidebar that are linked to the main content using scrollspy. This allows users to easily navigate to different sections of the main content by clicking on the corresponding headings i ...

Is there a way to automatically execute this function when the React component is loaded, without the need for a button click?

After spending a few days trying to figure this out, I'm hitting a wall. This ReactJS project is new for me as I usually work with C#. The goal is to create a print label component that triggers the print dialog when a link in the menu is clicked. Cu ...

What is the best way to access a JSON key array that may have only one element and is no longer iterable?

I've recently started working with JSON and I'm having difficulty handling keys that sometimes have sub-arrays, but other times do not. Usually, key2 and key3 contain sub-arrays: json_obj = json.loads(x) json_obj["key1"]["key2"][idx]["key3"][id ...

Error: The function "JSON_BUILD_OBJECT" cannot be located

When conducting tests, I am utilizing the h2 database. The settings for my test h2 database are as follows: private static final String JDBC_URL = "jdbc:h2:mem:test;MODE=PostgreSQL;DB_CLOSE_DELAY=-1"; Connection connection = DriverManager.getConn ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...