dan_vitch
dan_vitch

Reputation: 4559

Populate an array with value of json object

I am trying to populate an array with the text value of a json obejct based off values from another array

my code is:

var DemoOptions = {
  "One" : 1,
  "Two" : 2,
  "Three" : 3,
  "Four" : 4,
  "Five" : 5
};

var OldArray = [1,3,5];
var NewArray = [];


$.each(OldArray,function(x, item){
    NewArray.push(DemoOptions.item);
});

NewArray should now be:

NewArray ["One", "Three", "Five"]   

Upvotes: 0

Views: 1500

Answers (2)

Paul
Paul

Reputation: 141839

If DemoOptions was flipped like:

var DemoOptions = {
  1: "One",
  2: "Two",
  3: "Three",
  4: "Four",
  5: "Five"
};

you could do this very easily, because you just need to iterate through OldArray one and push the respective value (mapped by DemoOptions) into NewArray. Since there is probably a good reason you have it the other way, you should create this flipped copy dynamically and then fill your new array:

var DemoOptions = {
  "One" : 1,
  "Two" : 2,
  "Three" : 3,
  "Four" : 4,
  "Five" : 5
};

var OldArray = [1,3,5];


var flipped = {};
for(var key in DemoOptions)
    flipped[DemoOptions[key]] = key;

var NewArray = [];
for(var i = 0; i < OldArray.length; i++)
    NewArray.push(flipped[OldArray[i]]);

Upvotes: 3

curtisdf
curtisdf

Reputation: 4210

Too bad DemoOptions isn't indexed by the numeric value instead of by the string value. Anyway, how about this:

for (var index in OldArray) {
    var value = OldArray[index];

    for (var demoString in DemoOptions) {
        if (DemoOptions.hasOwnProperty(demoString)) {
            var demoValue = DemoOptions[demoString];
            if (value == demoValue) {
                NewArray.push(demoString);
                break;
            }
        }
    }
}

Upvotes: 1

Related Questions