-5

I need data structure like mokeData2 and sources data was like mokeData.

How can I convert mokeData to mokeData2 in javascript?

const mokeData = ["Friday 07:07:00", "Sunday 12:05:00"];
const mokeData2 = [{ Friday: "07:07:00", Sunday: "12:05:00" }];
DecPK
  • 24,537
  • 6
  • 26
  • 42
JackMusk
  • 11
  • 3
  • 1
    Why is the result an array if it is always going to have exactly one element?? What have you done to achieve that goal? – trincot Nov 20 '21 at 10:00
  • 1
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Nov 20 '21 at 10:01
  • I got data from server was like mokeData and need inject to a table in one column, so that's why I need data structure like mokeData2. – JackMusk Nov 20 '21 at 10:19

1 Answers1

3

1) You can easily achieve the result using Object.fromEntries and map

const mokeData = ["Friday 07:07:00", "Sunday 12:05:00"];
const mokeData2 = [{ Friday: "07:07:00", Sunday: "12:05:00" }];

const result = [Object.fromEntries(mokeData.map((s) => s.split(" ")))];
console.log(result);

2) You can also use reduce here as:

const mokeData = ["Friday 07:07:00", "Sunday 12:05:00"];
const mokeData2 = [{ Friday: "07:07:00", Sunday: "12:05:00" }];

const result = [
  mokeData.reduce((acc, curr) => {
    const [key, value] = curr.split(" ");
    acc[key] = value;
    return acc;
  }, {}),
];
console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • can't use 1) cuz I'm using next.js and 2) was good THANKS ALOT! – JackMusk Nov 20 '21 at 10:15
  • Would you mind If you can [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) my answer if it solved your issue? – DecPK Nov 20 '21 at 15:50