skip to Main Content
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 above code works fine.
But I have to find out if the part number matches the following part; if not, the partSupplier will be added to the following json; else not.

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

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

I tried the following, but the partSupplier value is empty:

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

The result from the console:

partSupp
It does not return any value.

I am using console.log to test the output before plugging the code.

2

Answers


  1. Use JSON.parse to get an array from the string, then use Array#find to get the object with a matching part.

    const part_str = '[{"part":"00000PD","partSupplier":"DELL"}]';
    const arr = JSON.parse(part_str);
    const match = arr.find(o => o.part.includes("00000PD"));
    if (match) {
      console.log(match.partSupplier);
    }
    Login or Signup to reply.
  2. This makes a modification to your original questions.

    The highlight is at like, 5, where the part_str is converted to JSON array, then like 7 picked the first item – I assume this is what you want to do.

    Then check if the partObj.part contains the particular string to get the partSupplier, else return "HP"

    Finally use the information to create a siteInfo object before pushing it to the siteList object

    var siteList = {
      siteInfo []
    };
    var part_str = '[{"part":"00000PD","partSupplier":"DELL"}]';
    
    const partArr = JSON.parse(part_str)
    
    var partObj = partArr[0]
    var partSubpp = partObj?.part?.includes("00000PD") ? partObj.partSupplier : "HP"
    
    siteInfo = {
      "Parts_Num": part,
      "partSupplier": partSupp
    }
    siteList.siteInfo.push(siteInfo);
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search