0

Say I have:

var Certificated = {}

Sub items are added dynamically and variate. Possible outcome:

var Certificated = {
    Elementary: ["foo","bar", "ball"]
    MiddleSchool: ["bar", "crampapydime"]
};

I want to do the following:

Certificated.Elementary = Certificated.Elementary.join("");

Except I need it to do that on all of the objects inside.

Keep in mind I can't know for sure the titles of nor how many objects will be inside Certificated.

My question is how can I use .join("") on all elements inside Certificated, without calling each one specifically?

EDIT: I am aware .join() is for arrays and the objects inside Certificated are going to be arrays. Therefore the join method.

1
  • 1
    JSON.stringify(Certificated)? Commented Feb 13, 2013 at 17:37

1 Answer 1

2

Does this work?

for (var key in Certificated) {
    if (Certificated.hasOwnProperty(key)) {
        Certificated[key] = Certificated[key].join("");
    }
}

It loops through all properties of Certificated, and makes a quick safe check for the key being a real property, then uses bracket notation - [""] - to do your join.

Quick question - are you sure you want to use join? I know you just provided an example, but you can't call join on a string...it's for arrays. Just wanted to make sure you knew.

Here's a jsFiddle of my code working with arrays being used for the properties:

http://jsfiddle.net/v48dL/

Notice in the browser console, the properties' values are strings because the join combined them with "".

Sign up to request clarification or add additional context in comments.

2 Comments

+1 for the key test! And yes, I updated my question to clarify that I planned to use the .join() on an array. I figured it was implied.
@JonnySooter Awesome, glad it helped. I thought you were implying, but I didn't want to assume too much. Nonetheless, I would've been glad to work with you if I hadn't understood :)

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.