-2

I have an array of strings like this:

    const array = [
       "date: 1679534340367, price: 27348.6178237571831766",
       "date: 1679534340367, price: 27348.6178237571831766",
       "date: 1679534340367, price: 27348.6178237571831766",
       "date: 1679534340367, price: 27348.6178237571831766",
       "date: 1679534340367, price: 27348.6178237571831766"
    ]

How can i convert it to an array of objects to look like this:

   const array = [
      {"date": 1679534340367, "price": 27348.6178237571831766},
      {"date": 1679534340367, "price": 27348.6178237571831766},
      {"date": 1679534340367, "price": 27348.6178237571831766},
      {"date": 1679534340367, "price": 27348.6178237571831766},
      {"date": 1679534340367, "price": 27348.6178237571831766},
   ]
1
  • Javascript Numbers don't have the amount of precision required to accurately store "price" exactly as you have it. Commented Mar 23, 2023 at 23:09

2 Answers 2

2

You can use .replace with regexp to escape object keys, wrap it with {}, and convert to objects using JSON.parse()

array.map((i) => {
    let item = i;

    // escape "date" key
    item = item.replace(/date:/, '"date":');

    // escape "price" key
    item = item.replace(/price:/, '"price":');

    // wrap string with curly braces
    item = `{${item}}`;

    // call JSON.parse func
    return JSON.parse(item );
})

Or without intermediate steps:

array.map((item) =>
  JSON.parse(
    `{${item.replace(/date:/, '"date":').replace(/price:/, '"price":')}}`,
  ),
);
Sign up to request clarification or add additional context in comments.

Comments

1

There are several options, the best in my opinion is using regular expressions:

const array = [
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766"
];

const newArray = array.map(str => {
  const matches = str.match(/date: ([\d.]+), price: ([\d.]+)/);
  return { date: Number(matches[1]), price: Number(matches[2]) };
});

console.log(newArray);

In addition, you can also use a map and split:

const array = [
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766",
   "date: 1679534340367, price: 27348.6178237571831766"
];

const newArray = array.map(str => {
  const parts = str.split(", ");
  const date = parts[0].split(": ")[1];
  const price = parts[1].split(": ")[1];
  return { date: Number(date), price: Number(price) };
});

console.log(newArray);

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.