0

I've got a JSON object like this

var test = {
    "value1": "",
    "array1": {
       "value2": 0,
       "value3": 0
    }
}

Now I want to Iterate over array1 in the test JSON and multiply the values and store them again ...

I tried it this way but it doesn't store it

jQuery.each(test.array1, function (i, val) {
    test.array1.i = val * 1.3;
});

The multiplication works fine .. But how to restore it properly?

4
  • 4
    This is an Object literal, not an array Commented Mar 28, 2016 at 13:49
  • how should it looks like that it works like I expected ? Commented Mar 28, 2016 at 13:51
  • It's not really clear what you're asking. Could you post your expected output? Commented Mar 28, 2016 at 13:51
  • You really don't even need val at all, you can just use *=. Also, a plain old for..in loop is even better. Commented Mar 28, 2016 at 14:55

4 Answers 4

3

You can use Array#forEach on keys array which are get by using Object.keys().

Object.keys(test.array1).forEach(function(key) {
    test.array1[key] *= 1.3;
});

Using Arrow function:

Object.keys(test.array1).forEach(key => test.array1[key] *= 1.3);

var test = {
    "value1": "",
    "array1": {
        "value2": 10,
        "value3": 30
    }
};

Object.keys(test.array1).forEach(function(key) {
    test.array1[key] *= 1.3;
});

console.log(test);

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

1 Comment

Wow, a plain javascript solution that's just as concise as jQuery
2

Use test.array1[i] instead of test.array1.ilike following.

jQuery.each(test.array1, function (i, val) {
    test.array1[i] = val * 1.3;
});

Comments

2

Do it like this:

var test = {
    "value1": "",
    "array1": {
       "value2": 1,
       "value3": 0
    }
}
jQuery.each(test.array1, function (i, val) {
                    console.log(i, val)
                    test.array1[i] = val * 1.3;//instead of test.array1.i = val * 1.3; use the bracket notation
                });

console.log(test)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

2

Without jQuery it can be done like this:

var test = {
  "value1": "",
  "array1": {
    "value2": 1,
    "value3": 2
  }
}

for (key in test.array1) {
  test.array1[key] *= 1.3;
}

console.log(test);

Run the snippet to check how it works.

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.