2

I have a javascript object converted using stringify that looks like this..

var myJSON = JSON.stringify(response);

{"0":{"trigger":17},"1":{"trigger":3},"2":{"trigger":40},"3":{"trigger":4},"4":{"trigger":19},"5":{"trigger":70},"6":{"trigger":80},"7":{"trigger":0},"8":{"trigger":0},"9":{"trigger":5},"10":{"trigger":4}}

I am trying to create an array but only of the value of trigger.

Should I loop through the response and do it that way or is there a better way like map?

3 Answers 3

5

You can use map method on Object.values.

const json = {"0":{"trigger":17},"1":{"trigger":3},"2":{"trigger":40},"3":{"trigger":4},"4":{"trigger":19},"5":{"trigger":70},"6":{"trigger":80},"7":{"trigger":0},"8":{"trigger":0},"9":{"trigger":5},"10":{"trigger":4}}

const arr = Object.values(json).map(({trigger}) => trigger);
console.log(arr)

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

1 Comment

Thank you, this seemed like the most straightforward method. Works great
3

You may get all the values from the object using Object.values and then apply Array.map on the collection to get the values of trigger only:

const obj = {"0":{"trigger":17},"1":{"trigger":3},"2":{"trigger":40},"3":{"trigger":4},"4":{"trigger":19},"5":{"trigger":70},"6":{"trigger":80},"7":{"trigger":0},"8":{"trigger":0},"9":{"trigger":5},"10":{"trigger":4}};

const arr = Object.values(obj).map(item => item.trigger);
console.log(arr);

Comments

2

Use for..in to iterate over the object and push the value to trigger to another array

let data = {
  "0": {
    "trigger": 17
  },
  "1": {
    "trigger": 3
  },
  "2": {
    "trigger": 40
  },
  "3": {
    "trigger": 4
  },
  "4": {
    "trigger": 19
  },
  "5": {
    "trigger": 70
  },
  "6": {
    "trigger": 80
  },
  "7": {
    "trigger": 0
  },
  "8": {
    "trigger": 0
  },
  "9": {
    "trigger": 5
  },
  "10": {
    "trigger": 4
  }
}
let arrVal = [];

for (var keys in data) {

  arrVal.push(data[keys].trigger)
};
console.log(arrVal)

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.