3

I have an array of an object with dynamic keys

response = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}];

I want to flatten this array of an object into a single array

Output = [1, 1, 1, 0, 0]

I tried the following:

const test2 = this.response.map(obj => {
    Object.keys(obj).map(function(key){
        return obj[key]
    })
});

const test = this.response.reduce(function(prev, curr){
    console.log(curr)
    return (curr) ? prev.concat(curr): prev;
},[]);

4 Answers 4

7

You can just use map and object.values

response = [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}]
const vals = response.map(o => Object.values(o)[0])

console.log(vals)

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

2 Comments

Type '{}[]' is not assignable to type 'number[]'. when used on the chart but works perfect on the concept
No clue why that error would occur with that code above.
5

You can use .map() with .concat():

let data =   [{"1": 1}, {"2": 1}, {"3": 1}, {"4": 0}, {"5": 0}];
      
let result = [].concat(...data.map(Object.values));

console.log(result);

Comments

1

Use reduce and for..in to loop over the object

let response = [{
    "1": 1
  },
  {
    "2": 1
  },
  {
    "3": 1
  },
  {
    "4": 0
  },
  {
    "5": 0
  }
]

let k = response.reduce(function(acc, curr) {
  for (let keys in curr) {
    acc.push(curr[keys])

  }
  return acc;
}, [])
console.log(k)

Comments

1

response = [{"1": 1},{"2": 1},{"3": 1},{"4": 0},{"5": 0}]

var newArray = []
for (element of response) {
  Object.keys(element).map(key => {
    newArray.push(element[key])
  })
}


console.log(newArray)

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.