0

How can I convert a json object ["gen001", "abC0002"} to {"GEN001","ABC0002"] using Underscore.j?

http://jsfiddle.net/Kc9gh/

var func = function(greeting){ return greeting + ': ' + this.name };
func = _.bind(func, {name: 'moe'}, 'hi');
func();
1
  • Is that an array or an object? Commented Nov 24, 2013 at 17:30

1 Answer 1

1

First, of all {"gen001", "abC0002"} is not a object.
If you need an object with keys gen001 and abC0002, when you should also specify values:

var input = {"gen001":"some value", "abC0002":"some other value"};

In that case you can use _.each to loop through object properties and build another object with the keys you want:

var input = {"gen001":"some value", "abC0002":"some other value"},
    output = {};
_.each(
    input,
    function(element, index, list) {
        output[index.toUpperCase()] = element;
    }
);
console.log(output);

If you have an array:

var input = ["gen001", "abC0002"];

you can use _.map:

var input = ["gen001", "abC0002"];
var output = _.map(
    input,
    function(element) {
        return element.toUpperCase();
    }
);
console.log(output);
Sign up to request clarification or add additional context in comments.

4 Comments

_.map uses _.each, so your second snippet works in both cases.
@psquared: But it does return an array even for objects.
@psquared: Second snippet works, but returns array of values from input object, not keys. That's why it cannot be used without additional modifications.
Ah, very good point. I was fixated on the array-looking values in the question.

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.