0

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"]   

2 Answers 2

3

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]]);
Sign up to request clarification or add additional context in comments.

Comments

1

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

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.