-1

So I have this string (line-breaks added):

var str = '[{"id":1,"type":"one","status":"pending","user_id":2},
            {"id":2,"type":"two","status":"pending","user_id":14},
            {"id":3,"type":"three","status":"queue","user_id":5},
            {"id":4,"type":"four","status":"queue","user_id":8 }]';

What algorithm can I use to get all type values in one array? So the result would be "one", "two", "three", "four".

FunKction
  • 3
  • 2
  • 1
    This looks like JSON, and should probably be handled that way. – Nathan Tuggy Jun 03 '15 at 01:18
  • It is JSON, but i'm curious about the ways I could handle this with string operators. – FunKction Jun 03 '15 at 03:37
  • No, you **don't** want to use string operators. Since it's an array (after you parse it), I suggest a "loop" to loop over the elements of the array. Then you can retrieve the `type` property from each element and put it in a list. By the way, how do you want to handle duplicates? –  Jun 03 '15 at 03:58

3 Answers3

2

You can parse the string to a object then use .map() to create an array of all type values

var str = '[{"id":1,"type":"one","status":"pending","user_id":2},{"id":2,"type":"two","status":"pending","user_id":14},{"id":3,"type":"three","status":"queue","user_id":5},{"id":4,"type":"four","status":"queue","user_id":8 }]';

var array = JSON.parse(str);
var myarray = array.map(function(item) {
  return item.type;
});
console.log(myarray);
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0
var obj = JSON.parse(str);
var types = [];
for (var i in obj) {
    types.push(obj[i].type);
}

That should get you the types you need and stick them into the types array.

Kilenaitor
  • 654
  • 6
  • 17
  • 2
    Although it may not matter in this case, in general the use of `for...in` is discouraged for looping over arrays, and it's best not to get into the habit of doing that. See http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea. –  Jun 03 '15 at 04:01
0

If you're writing ES6, then following @ArunPJohny:

array.map(elt => elt.type)

or

[ for (elt of array) elt.type ]