简体   繁体   中英

Covert array to json object

I have an array like this

[ 'quality',
  'print-quality: 4',
  'x-dimension',
  'Value: 21590',
  'Value: y-dimension',
  'Value: 27940',
  'Value: ',
  'Value: media-bottom-margin',
  'Value: 0',
  'Value: media-left-margin',
  'Value: 0',
  'Value: media-right-margin',
  'Value: 0',
  'Value: media-top-margin',
  'Value: 0',
  'Value: ' ]

am trying to convert this array to a json in the following format

 { "quality": "print-quality: 4",
  "x-dimension": "21590",
  "y-dimension": "27940", 
  "media-bottom-margin": "0",
  "media-left-margin" : "0",
 "media-right-margin": "0",
  "media-top-margin" : "0" 
 }

I need to remove all 'Value' string also how it can be obtain in the above format

You can't create an associative array like that because JavaScript doesn't have associative arrays. But you can create an object, which is really what you want here.

Here's one way to do it:

var data = [ 'quality',
        'print-quality: 4',
        'x-dimension',
        'Value: 21590',
        'Value: y-dimension',
        'Value: 27940',
        'Value: ',
        'Value: media-bottom-margin',
        'Value: 0',
        'Value: media-left-margin',
        'Value: 0',
        'Value: media-right-margin',
        'Value: 0',
        'Value: media-top-margin',
        'Value: 0',
        'Value: ' ],
    cleanData,
    newData = {}; // initialize the new object

cleanData = data
    .map( function(x) { return x.replace(/^Value: /, ''); }) // remove leading "Value: " 
    .filter( function (x) { return !x.match(/^$/); } ); // strip empty values 

for (i = 0; i < cleanData.length; i += 2) { // loop over the cleaned-up array
    newData[cleanData[i]] = cleanData[i + 1];
}

The result is that newData (in JSON form for readability) is:

{
    "quality":"print-quality: 4",
    "x-dimension":"21590",
    "y-dimension":"27940",
    "media-bottom-margin":"0",
    "media-left-margin":"0",
    "media-right-margin":"0",
    "media-top-margin":"0"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM