0

I have an array that outputs as below (using console.log):

["{"Heading":"EmployeeNumber","Type":"Text"}",
 "{"Heading":"First Name","Type":"Text"}", 
 "{"Heading":"Last Name","Type":"Text"}", 
 "{"Heading":"Payroll","Type":"Text"}", 
 "{"Heading":"MonthlyEmployeeCost","Type":"Text"}",           
 "{"Heading":"MonthlyEmployerCost","Type":"Text"}", 
 "{"Heading":"Benefit","Type":"Text"}", "{"Heading":"DOB","Type":"Text"}"]

I would like to retrieve the value for each Type within the array. So in the example above I would expect "Text" to pull through for each Type.

Please can someone clarify how this is done?

Vickel
  • 7,879
  • 6
  • 35
  • 56
user2547766
  • 111
  • 7

2 Answers2

1

First, this formatting is very odd. I'm guessing you have some server-side process that is encoding each object, putting the encoding in an Array, and then encoding the Array. This is problematic.

Anyway, each item in your array is encoded as JSON data, so you need to parse each one separately to get its Type.

You can use .map() to collect the results.

var data = ['{"Heading":"EmployeeNumber","Type":"Text"}', '{"Heading":"First Name","Type":"Text"}', '{"Heading":"Last Name","Type":"Text"}', '{"Heading":"Payroll","Type":"Text"}', '{"Heading":"MonthlyEmployeeCost","Type":"Text"}', '{"Heading":"MonthlyEmployerCost","Type":"Text"}', '{"Heading":"Benefit","Type":"Text"}', '{"Heading":"DOB","Type":"Text"}'];

var result = data.map(s => JSON.parse(s).Type);

console.log(result);

I assume the double quotes on the outside of each string were just the result of a console display, so I switched them to single quotes.

But again, the encoding likely needs to be fixed elsewhere.

  • I think it's just the way Chrome's console shows arrays of strings. Try it yourself with your `data` array ~ `console.log(data)` – Phil Feb 14 '18 at 00:26
  • @Phil: I was talking more about having separate JSON strings in an array being odd. I have a feeling that the OP's server code is encoding each object, putting it into an array, and then encoding again. So when it gets to the browser, `JSON.parse` only decodes one level of encoding. –  Feb 14 '18 at 02:37
  • Good point. It does look like double-encoding – Phil Feb 14 '18 at 02:59
0

Use for of iteration.

var arr = [{"Heading":"EmployeeNumber","Type":"Text"}, {"Heading":"First Name","Type":"Text"}, {"Heading":"Last Name","Type":"Text"}, {"Heading":"Payroll","Type":"Text"}, {"Heading":"MonthlyEmployeeCost","Type":"Text"}, {"Heading":"MonthlyEmployerCost","Type":"Text"}, {"Heading":"Benefit","Type":"Text"}, {"Heading":"DOB","Type":"Text"}];

for (obj of arr) {
    console.log(obj.Type);
}

Below code will output all Type data which is Text or you can store it to another array for your own usage.

Dencio
  • 518
  • 3
  • 12