0

I have the following json object:

[{"i_value":"1","i_value_2":"1"},
{"i_value":"24","i_value_2":"24"}]

Then I have the following loop:

let setData = [];
for (let i = 0; i < response.data.length; i++) {
    if ('access key name' === 'i_value') {
        setData.push(response.data[i].i_value)
    }
}
setData = setData.map(Number);
console.log(setData);

I only want to populate the new setData array when the key name === i_value not i_value_2

I tried the following:

let setData = [];
let keys = Object.keys(response.data);
for (let i = 0; i < response.data.length; i++) {
    if (keys[i] === 'i_value') {
        setData.push(response.data[i].i_value)
    }
}
setData = setData.map(Number);
console.log(setData);

But this doesn't work. Any thoughts on this?

0

2 Answers 2

5

Just take the original data and .map, extracting the i_value property:

const input = [{"i_value":"1","i_value_2":"1"},
{"i_value":"24","i_value_2":"24"}];

console.log(
  input.map(({ i_value }) => Number(i_value))
);

Also note that there's no such thing as a JSON object. If you have an object, you just have an object; JSON format is a format for strings that can be transformed into objects via JSON.parse.

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

1 Comment

Helpfull! And thanks for pointing out my misunderstanding about JSON object :-).
2

You can use map() to create a new array with the results of calling a provided function on every element in the calling array in the following way:

var response = {}
response.data = [{"i_value":"1","i_value_2":"1"},
{"i_value":"24","i_value_2":"24"}]

let setData = response.data.map(o => Number(o.i_value));

console.log(setData);

2 Comments

And this actually saves me from doing the loop! Many thanks for this!
@dexter, you are most welcome. And yes, these are the the beauty of array functions......

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.