JS - Create function of JSON object that has properties

0 votes
178 views
added Jul 18, 2019 in Javascript by LC Marshal Captain (25,790 points)
// JSON object that has several properties and unique id as key.
// Setup
var kedai = {
    "11": {
      "brand": "Ford",
      "bodytype": "double cab",
      "variant": [ 
        "xlt", 
        "xls" 
      ]
    },
    "12": {
      "brand": "Audi",
      "bodytype": "hatchback",
      "variant": [ 
        "s3", 
        "s3 premium" 
      ]
    },
    "13": {
      "brand": "Ford",
      "variant": [ ]
    },
    "14": {
      "brand": "Land rover"
    }
};
// Keep a copy of the collection for tests
var kedaicopy = JSON.parse(JSON.stringify(kedai));

// Only change code below this line
function updateKedai(id, prop, value) {
  if (prop === "tracks" && value !== "") {
   if(kedai[id][prop]) {
    kedai[id][prop].push(value);
   }
   else {
    kedai[id][prop]=[value];
   }
  } else if (value !== "") {
    kedai[id][prop] = value;
  } else {
    delete kedai[id][prop];
  }

  return kedai;
}

// Alter values below to test your code
updateKedai(11, "brand", "ford");

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...