1

Please somebody guide me in the right way

i have this object

myObject = {"Timer13":{"Arm":0,"Mode":0},"Timer14":{"Arm":1,"Mode":1}}

And i need get this array

[{"timer":"Timer13", "Arm":0,"Mode":0},{"timer":"Timer14","Arm":1,"Mode":1}]

I tried several ways, i dont get it;

it is my incomplete result using map

var result  = Object.keys(myObject).map((i) => myObject[i]);

and i get

 [{"Arm":0,"Mode":0},{"Arm":1,"Mode":1}]

3 Answers 3

2

Maybe try appending a key and add the rest of the elements to the object before returning from the map.

var myObject = {"Timer13":{"Arm":0,"Mode":0},"Timer14":{"Arm":1,"Mode":1}}

var result = Object.keys(myObject).map(elem => {
    return {timer: elem, ...myObject[elem]}
})

console.log(result)

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

1 Comment

Nice answer. You can return an object from an arrow function by surrounding it in parens to avoid the return statement: Object.keys(myObject).map(elem => ({timer: elem, ...myObject[elem]}))
1

You could get the entries and map new objects by assigning the parts.

var object = { Timer13: { Arm: 0, Mode: 0 }, Timer14: { Arm: 1, Mode: 1 } },
    array = Object
        .entries(object)
        .map(([timer, values]) => Object.assign({ timer }, values));

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You can use reduce to achieve that playing with Current Value (curr) an Accumulator (all) also destructing your array can be helpful for a cleaner code. [timer,obj] timer : curr[0] and the obj is curr[1]

obj = {
  "Timer13": {
    "Arm": 0,
    "Mode": 0
  },
  "Timer14": {
    "Arm": 1,
    "Mode": 1
  }
}

const res = Object.entries(obj).reduce((all, [timer, obj]) => {
  all.push({
    timer,
    ...obj
  })
  return all;
}, [])


console.log(res)

1 Comment

i don't understand why i am getting -1 :) the output is correct i think

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.