1

I'm attempting to parse a csv file as JSON, which I have done, and it's working fine.

I now need to rename the 'product_code' key throughout the JSON to 'value', and also duplicate it (renaming the second iteration 'label'). The value will remain the same for both. I cannot edit the csv file, and this needs to be done in JavaScript / jQuery.

Hopefully this will explain it more clearly:

Existing:

{
    "brand":"BrandName1",
    "product_code":"001",
    "product_name":"White Picture Frame",
    "product_barcode":"1009842098"
},
{
    "brand":"BrandName2",
    "product_code":"002",
    "product_name":"Yellow Picture Frame",
    "product_barcode":"0982149872"
}

And I wish to change this to:

{
    "brand":"BrandName1",
    "value":"001",
    "label":"001",
    "product_name":"White Picture Frame",
    "product_barcode":"1009842098"
},
{
    "brand":"BrandName2",
    "value":"002",
    "label":"002",
    "product_name":"Yellow Picture Frame",
    "product_barcode":"0982149872"
}

This is so it can be used with jQuery Autocomplete.

Any help much appreciated! I'm a newbie when it comes to JSON.

traummaschine
  • 439
  • 8
  • 18
  • 1
    If you've already parsed it, this has nothing to do with JSON. It's just a JavaScript object. Do whatever you would do in JavaScript to manipulate object properties. – user229044 Oct 06 '15 at 14:29
  • I'd say the simplest solution is to generate the appropriate JSON in the first place. You don't give any context to help on that. – Álvaro González Oct 06 '15 at 14:57

3 Answers3

3

The best way to do this would be to JSON.parse() your data, then iterate through the items in the object it builds and add the keys you'd like. Something like:

var data = JSON.parse(myJsonString);
for (var i = 0; i < data; i++) {
    data[i].value = data[i].product_code;
    data[i].label = data[i].product_code;
    data[i].product_code = undefined;
}

EDIT: Instead of changing product_code to undefined, you can remove it completely with delete data[i].product_code;. See here for more info: https://stackoverflow.com/a/3455416/5169684.

Community
  • 1
  • 1
Adam Mazzarella
  • 763
  • 1
  • 7
  • 14
1

Should be:

new.value = existing.product_code;
new.label = existing.product_code;

As far as existing, properties that you want to remove. Use delete.

delete existing.product_code;
beautifulcoder
  • 10,832
  • 3
  • 19
  • 29
0

I ended up using the following code, which works fine - thanks for putting me on the right track...

var i;

for(i = 0; i < productList.length; i++){
    productList[i].value = productList[i]['product_code'];
    productList[i].label = productList[i]['product_code'];
    delete productList[i].product_code;
}
traummaschine
  • 439
  • 8
  • 18