0

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)?

1
  • JSON.parse and then for...in Commented Oct 10, 2014 at 18:53

3 Answers 3

3

Iterate the keys and push the values:

var stringarray = [];
for (var key in data) {
    stringarray.push(data[key]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

hey tymeJV, thanks for your answer, but i tried this before and i'll get this: {,",m,e,s,s,a,g,e,1,",:,",h,a,l,l,o,",,,",m,e,s,s,a,g,e,2,",:,",w,e,l,t,!,",}
Where does message1 come from?
0

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]);
}

2 Comments

hey izzey, thanks for your answer, but i tried this before and i'll get this: {,",m,e,s,s,a,g,e,1,",:,",h,a,l,l,o,",,,",m,e,s,s,a,g,e,2,",:,",w,e,l,t,!,",}
How does your original object look?
0

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.