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
Use
JSON.parse
to get an array from the string, then useArray#find
to get the object with a matchingpart
.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 thepartSupplier
, else return"HP"
Finally use the information to create a
siteInfo
object before pushing it to thesiteList
object