IJavaScript | Guqula iArray ibe yinto yeJSON

Ibhlog

IJavaScript | Guqula iArray ibe yinto yeJSON

IJavaScript | Guqula iArray ibe yinto yeJSON

Yintoni iJSON?

IJSON ithetha ukuba iNqaku leNqaku leJavaScript. I-JSON yifomathi yokutshintshiselana ngokulula kakhulu yedatha yotshintshiselwano lwedatha phakathi kweseva-icala kunye necala labathengi elikhawulezayo kwaye kulula ukulicacisa nokulivelisa.

1. Guqula iArray ibe yinto yeJSON JavaScript

Ungasebenzisa iJSON.stringify ukuguqula uluhlu lube ngumtya wefomathi yeJSON kwiJavaScript.

ikhadi lisabela-inzalelwane

Masithi kukho uluhlu olufana ne- [6, 7, 8, 9]. Ukuba ufuna ukuguqula olu luhlu lube yinto yeJSON kwiJavacript. Makhe sibone umzekelo ongezantsi

Ngaphambili:

var arr = [5, 6, 7, 8]; var arrayToString = JSON.stringify(Object.assign({}, arr)); // convert array to string var stringToJsonObject = JSON.parse(arrayToString); // convert string to json object console.log(stringToJsonObject);

Iziphumo:

{ '0': 5, '1': 6, '2': 7, '2': 8 }

Apha,

izinto uiqalisa
  • 1.JSON.stringify () kunye Object.assign () indlela yokuguqula uluhlu lube ngumtya weJSON.
  • 2.JSON.parse () indlela yokuguqula umtya ube yinto yeJSON kwiJavacript.

2. Ukuguqula into ibe luhlu

Xa uguqula into ibe luhlu, siya kusebenzisa .entries() indlela evela Object iklasi. Oku kuyakuguqula into yethu ibe luluhlu oluhlu. Uluhlu ngalunye lwendlu luluhlu lwamaxabiso amabini apho into yokuqala isisitshixo kwaye into yesibini lixabiso.

Ngaphambili:

const obj = {'1':5,'2':7,'3':0,'4':0,'5':0,'6':0,'7':0,'8':0,'9':0,'10':0,'11':0,'12':0}; console.log(Object.entries(obj));

3. Guqula i-2-dimensional (2d) arrays to JSON Object JavaScript

Masithi kukho uluhlu olunje nge

var arr = [ ['Status', 'Name', 'Marks', 'Position'], ['active', 'Akash', 10.0, 'Web Developer'], ['active', 'Vikash', 10.0, 'Front-end-dev'], ['deactive', 'Manish', 10.0, 'designer'], ['active', 'Kapil', 10.0, 'JavaScript developer'], ['active', 'Manoj', 10.0, 'Angular developer'], ];

Ukuba ufuna ukuguqula olu luhlu lube yinto yeJSON kwiJavacript. Masibone umzekelo ongezantsi:

Iindawo zikaGoogle zibeka umzekelo ogqibeleleyo ngaphandle kwemephu

Ngaphambili:

//array. var arr = [ ['Status', 'Name', 'Marks', 'Position'], ['active', 'Akash', 10.0, 'Web Developer'], ['active', 'Vikash', 10.0, 'Front-end-dev'], ['deactive', 'Manish', 10.0, 'designer'], ['active', 'Kapil', 10.0, 'JavaScript developer'], ['active', 'Manoj', 10.0, 'Angular developer'], ]; //javascript create JSON object from two dimensional Array function arrayToJSONObject (arr){ //header var keys = arr[0]; //vacate keys from main array var newArr = arr.slice(1, arr.length); var formatted = [], data = newArr, cols = keys, l = cols.length; for (var i=0; i

#javascript #Array #json