skip to Main Content

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},
   ]

2

Answers


  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);
    Login or Signup to reply.
  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":')}}`,
      ),
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search