Reputation: 1
I'm new in this community and I just started programming. I couldn't find anything about this topic, so i decided to start a new... if it's wrong please let me know.
Well, I've the following problem... i want to put the values of an JSON-Object into a string array in Javascript.
What I've got looks like this:
{"prop1":"hello","prop2":"world!"}
what i need should look like this
stringarray = [hello, world];
How can I get the values (hello & world) of the JSON object and put them into a string array without these special characters (", :) and without the properties (prop1, prop2)?
Upvotes: 0
Views: 56
Reputation:
A "modern" approach worth learning, is, after you've parsed the JSON into a JS object:
Object.keys(obj).map(function(k) { return obj[k]; });
What's going on here? First, we use Object.keys
to create an array of all the keys in the object, so ['prop1', 'prop2']
. Then we use the handy map
function on arrays to transform each of the elements of that array based on a function we give it, which in this case is to retrieve the value for that key from the object.
We could bundle this into a handy little function as follows:
function objectValues(obj) {
return Object.keys(obj).map(function(k) { return obj[k]; });
}
Believe it or not, there is no such thing built into JavaScript, although the Underscore library has _.values
.
Then you could do something as simple as
objectValues(JSON.parse(json))
Upvotes: 0
Reputation: 1415
Use a for-loop to go through the object attributes
var obj = {"prop1":"hello","prop2":"world!"};
var array = [];
for(var key in obj){
array.push(obj[key]);
}
Upvotes: 0
Reputation: 104795
Iterate the keys and push the values:
var stringarray = [];
for (var key in data) {
stringarray.push(data[key]);
}
Upvotes: 3