I like to access/extract specific key values of "serviceCode" the array, how could i do that.
var x = {
"0": "{"carrierCode":"ups","serviceCode":"ups_ground","packageTypeCode":"ups_custom_package","currency":"USD","totalAmount":"28.66","baseAmount":"20.19","surcharges":[{"description":"Fuel Surcharge Ground","amount":"3.28"},{"description":"Residential Ground","amount":"2.01"},{"description":"Delivery Confirmation Signature","amount":"3.18"}],"zone":"8","quotedWeight":"25","quotedWeightType":"Actual"}",
"1": "{"carrierCode":"ups","serviceCode":"ups_second_day_air","packageTypeCode":"ups_custom_package","currency":"USD","totalAmount":"69.72","baseAmount":"54.94","surcharges":[{"description":"Fuel Surcharge - Domestic Air","amount":"9.55"},{"description":"Residential Express","amount":"2.05"},{"description":"Delivery Confirmation Signature","amount":"3.18"}],"zone":"208","quotedWeight":"25","quotedWeightType":"Actual"}",
"2": "{"carrierCode":"ups","serviceCode":"ups_next_day_air","packageTypeCode":"ups_custom_package","currency":"USD","totalAmount":"76.62","baseAmount":"60.85","surcharges":[{"description":"Fuel Surcharge - Domestic Air","amount":"10.54"},{"description":"Residential Express","amount":"2.05"},{"description":"Delivery Confirmation Signature","amount":"3.18"}],"zone":"108","quotedWeight":"25","quotedWeightType":"Actual"}"
};
const me = Object.create(x);
var arr = [];
$.each( me, function( index, value){
arr.push(value);
});
console.log(arr.carrierCode);
It always return undefined
3
Answers
The values in your array are JSON strings and must be first decoded to objects. Then you can retrieve the
serviceCode
values from them:Below javascript code will work without jQuery
You don’t need jQuery anymore to manipulate data, keep it for DOM.
Just map the object values with parsing them with
JSON.parse
.If the JSON is returned from the backend, I would ask the backender to provide it parsed.
If you need your data later I would suggest to mutate it into an array and parse it for later use including your case.
Btw stop using
var
– it’s legacy and creates many subtle bugs.But if you need the
serviceCode
property only:Another option is parse with a regex, it’s faster since you don’t need to parse the whole JSON (if you don’t need the rest of data later)