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

Warning: ComponentMounts has been renamed. Proceed with caution

I'm encountering a persistent warning in my application and I'm struggling to resolve it. Despite running npx react-codemod rename-unsafe-lifecycles as suggested, the error persists and troubleshooting is proving to be challenging. The specific w ...

How can I retrieve data from a script tag in an ASP.NET MVC application?

I'm struggling to figure out how to properly access parameters in a jQuery call. Here is what I currently have: // Controller code public ActionResult Offer() { ... ViewData["max"] = max; ViewData["min"] = min; ... return View(paginatedOffers ...

jQuery functions not functioning properly when triggered by an event

I encountered an issue with my page using jQuery and Bootstrap. Everything was functioning properly until I tried calling a function on an event, which resulted in the console showing an error message saying $(...).function is not a function. For example: ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

Disabling a specific dropdown within ng-repeat in AngularJS

I've encountered a problem with the ng-repeat in my HTML code: <div ng-repeat="a in items"> <div> <span>{{a.name}}</span> </div> <div> <select ng-model="a.c_id" ng-options="d.c_id as d.description ...

What is the proper way to utilize setTimeout in TypeScript?

Let's take a look at an example of how to use setTimeout in Angular and TypeScript: let timer: number = setTimeout(() => { }, 2000); However, upon compilation, you may encounter the following error message: Error TS2322: Type 'Timeout' ...

ERROR_UNSUPPORTED_ESM_URL_SCHEME - issue with next-sitemap plugin

I have a project utilizing next-sitemap with Node.js version v14.11.0. next-sitemap.config.js module.exports = { siteUrl: 'https://*****.com', generateRobotsTxt: true, robotsTxtOptions: { additionalSitemaps: [ 'htt ...

Executing javascript code that has been inserted into inner HTML is not functioning as expected

Trying to retrieve a response from another page, specifically named ajaxresponse.php, through an AJAX request. I also aim to execute some JavaScript actions on that ajaxresponse.php page, but the JavaScript code is not functioning as expected. Although I a ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

jQuery does not have the capability to access the href attribute through DOM manipulation

I've been trying to extract the href attribute from a link in my code and create a new link using that attribute. However, I'm facing an issue where the created link doesn't seem to work properly - it keeps showing a 404 error message like t ...

Steps for showcasing a automated slideshow

I'm currently working on creating a slideshow that automatically displays multiple images. While the first image shows up just fine, it doesn't seem to transition to the next one. var currentSlide = 0; displaySlides(); functio ...

What causes ngClick to stop working following $compile?

http://plnkr.co/edit/kL2uLPQu2vHHKIvRuLPp?p=preview Upon button click, the controller calls a service to compile HTML and inject it into the body. The compiled HTML (displaying "Hello World" from $scope.name) is referring to the scope of the controller, ...

Is there a way to verify the textbox value in MVC without the need for clicking submit or performing a postback

Exploring MVC for the first time. I am working on a Registration Form with 10 textboxes for id, name, address, etc. I need to validate if the entered Id is already in the database and display the status without requiring the user to click a submit button. ...

ExpressJS - Issue with POST Router resulting in 404 Error

I am currently getting acquainted with ExpressJS and am in the process of setting up a small todo list app while incorporating React. I have successfully retrieved my list of todos from a mysql database, however, I am encountering difficulties with the POS ...

Finding a quicker route to fulfill a commitment

When dealing with asynchronous behavior in a function, I often find myself creating a deferred and returning a promise. For example: var deferred = $q.defer(); //...some async operation return deferred.promise; However, sometimes I want to skip the async ...

You cannot render objects as a React child (discovered: object containing keys {id, name}). To display a collection of children, make sure to use an array instead

My goal is to retrieve data from an API and present it in a table using the material-table library. I suspect that I am struggling to properly manipulate objects and arrays. The response from my API is as follows: { "data": [ { " ...

Exploring the differences between scoping with let and without any scoping in

Within my code, there is a forEach loop containing a nested for loop. It's interesting that, even though I have a statement word = foo outside of the for loop but still inside the forEach loop, I can actually log the value of word after the entire for ...

Implementing script loading within the Angular scope

I'm attempting to load a custom script from the database based on client-side logic. I am having trouble figuring out how to make it function properly. Here is my controller code: 'use strict'; angular.module('youshareApp') . ...

Using Javascript, you can create a function that can disable or enable a text link based on

Here is the code snippet showcasing CSS styles and HTML elements: CSS: .enableLink{ font-family:Verdana, Geneva, sans-serif; font-size:12px; color:#069; padding-right:20px; text-decoration:underline; cursor:pointer; } .disableLink{ display:none; fon ...

What is the reason behind the C# button_clicked function not triggering the Javascript function?

When the user clicks the button, I want to test the C# code side. The method in the C# function should call a JavaScript function to display an alert with the results of a C# public variable. However, it seems that nothing is being called at all. At the bo ...