-1

I have a object like that:

var days = {
  0: 10,
  1: 40
  2: 20, 
  3: 15,
  4: 5,
  5: 18, 
  6: 9
};

I need to transform it to something like that:

var days2 = [
  {0:10},
  {1: 40},
  {2: 20},
  {3: 15},
  {4: 5},
  {5: 18},
  {6: 9},
];

I know that it's easy, but I don't have any idea

5
  • Please share your attempt. Commented Mar 20, 2018 at 9:40
  • It's days).map. Commented Mar 20, 2018 at 9:41
  • 4
    Wouldn't var days = [10, 40 20, 15, 5, 18, 9]; be even better? Commented Mar 20, 2018 at 9:41
  • it should be Object.keys(days).map( s => {return {[s]: days[s]} }) Commented Mar 20, 2018 at 9:44
  • 1
    This might already be answered. You can use lodash. Refer here Commented Mar 20, 2018 at 9:46

2 Answers 2

2

You could take all entries of the object and build new objects with key/value pairs.

var days = { 0: 10, 1: 40, 2: 20, 3: 15, 4: 5, 5: 18, 6: 9 },
    result = Array.from(Object.entries(days), ([k, v]) => ({ [k]: v }));
    
console.log(result);

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

Comments

0

You can use Object.keys and map

 Object.keys(days).map( key => {return { [key]: days[key] 

var days = {
  0: 10,
  1: 40,
  2: 20, 
  3: 15,
  4: 5,
  5: 18, 
  6: 9
};
var output = Object.keys(days).map( key => {return { [key]: days[key] } });

console.log(output);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.