stackoverlord
stackoverlord

Reputation: 25

What is the best way to deal with changing key names on a JSON?

I was wondering if there is a way to transform this JSON in a way that instead of having "2020-07-06" as a key we would have a field date: "2020-07-06". Its a large dataset so I can't manually change eveything.

{
  "2020-07-06": {
    "food": {
    },
  },
  "2020-07-07": {
    "food": {
      },
    },
  "2020-07-08": {
    "food": {
      },
    },
  }

Expected output:

{
  "date": "2020-07-06",
  "food": {
   },
  "date": "2020-07-07",
  "food": {
   },
  "date: "2020-07-08",
  "food": {
   },
}
    

Upvotes: 1

Views: 59

Answers (3)

stranded
stranded

Reputation: 322

You can use Object.entries and then map over it to create an array

const old = {
  "2020-07-06": {
      "food": {
    },
  },
  "2020-07-07": {
      "food": {
      },
    },
  "2020-07-08": {
      "food": {
      },
    },
    }

const newArray = Object.entries(old).map(([key, valueObject]) => {
  return { date: key, ...valueObject }
})

console.log(newArray)

Upvotes: 1

stacj
stacj

Reputation: 1120

Have a look at this snippet. Guess this is a way to start with.

const old = {
  "2020-07-06": {
      "food": {
    },
  },
  "2020-07-07": {
      "food": {
      },
    },
  "2020-07-08": {
      "food": {
      },
    },
}

const obj = Object.keys(old).map(e => {
   let res = old[e]
   res.date = e;
   return res;
});
console.log(obj);

Upvotes: -1

Greedo
Greedo

Reputation: 3559

The keys has to be unique, so the only clean way to solve this is using arrays. Here you have an example of solution:

const input = {
  "2020-07-06": {
    "food": {
    },
  },
  "2020-07-07": {
    "food": {
      },
    },
  "2020-07-08": {
    "food": {
      },
    },
  }
  
  const res = Object.keys(input).map((key) => {
    return {
      food: input[key].food,
      date: key
     }
  });
  
  console.log(res)

Upvotes: 1

Related Questions