0

I am reading a local csv file with ajax query , and then loading read values into an array.

This is how the string value looks like in the csv file :

"Tiger","Architect","800","DRP","5421","VFX"

after loading this string into the array , the array looks like this :

0: (6) ["Tiger", "Architect", "800", "DRP", "5421", "VFX"]

now I am trying to convert this above mentioned sting into a json object to look like this :

{
    "data": [
    {
    "0": "Tiger",
    "1": "Architect",
    "2": "800",
    "3": "DRP",
    "4": "5421",
    "5": "VFX"
    }]
}

by having all the values inside one object data

I tried this :

  var arrayToString = JSON.stringify(Object.assign({}, data1)); 
  var stringToJsonObject =  JSON.parse (arrayToString) ; 

it converts the array to json, but with length 6 where as I need the length to be 1

any way to do this ?

1
  • data is an array with an object at position 0 Commented Sep 6, 2021 at 7:09

2 Answers 2

2

I think you have almost done everything, when you create object - just wrap array in []

const arr = ["Tiger", "Architect", "800", "DRP", "5421", "VFX"];
    
var arrayToString = JSON.stringify(Object.assign({}, [arr])); 
var stringToJsonObject =  JSON.parse (arrayToString) ; 

console.log(stringToJsonObject);
Sign up to request clarification or add additional context in comments.

1 Comment

It works perfectly if there is just one row in csv , or one array of values , but It seems like when there are multiple rows or arrays it won't work ?
2

You can do this using Object.entries and Object.fromEntries.

const arr = ["Tiger", "Architect", "800", "DRP", "5421", "VFX"];

const result = {data: []};

result.data.push(Object.fromEntries(Object.entries(arr)));

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.