Home > database >  Javascript Object- replace default key values with new ones
Javascript Object- replace default key values with new ones

Time:10-21

Trying to solve this problem: keys containing arrays should be named as plurals. then return a new object that is a copy of the input but with any keys that contain arrays pluralized (an 's' added to the end.).

My approach is to loop into this new object and figure out whether the key is an array or not(Array.isArray(value). Once done that I have what I need which are the keys: (job, and favoriteShop) now my last step where I am stuck is to replace the default key values (job and favoriteShop) with the new ones which must be (jobs, favoriteShops)

 function pluraliseKeys(obj) {
  const newObj = { ...obj };
  for (const [key, value] of Object.entries(newObj)) {
    if (Array.isArray(value)) {
      console.log(key);
      *// here I would like to say that the keys (in this case job and favoriteShop are = jobs and favoriteShops)*
      newObj[key] = key   "s"; //not working
    }
  }

  return newObj;
}

console.log(
  pluraliseKeys({
    name: "Tom",
    job: ["writing katas", "marking"],
    favouriteShop: [
      "Paul's Donkey University",
      "Shaq's Taxidermy Shack",
      "Sam's Pet Shop",
    ],
  })
);

I am trying different solutions but with no results.

the result should be like:

name: 'Tom',
      jobs: ['writing katas', 'marking'],
      favouriteShops: [
        "Paul's Donkey University",
        "Shaq's Taxidermy Shack",
        "Sam's Pet Shop"

there is a way to achieve this following the way I am doing? or should I need to change the approach?

thank you for your support.

CodePudding user response:

function pluraliseKeys(obj) {
  return Object.fromEntries(Object.entries(obj).map(([k,v])=>[Array.isArray(v)?`${k}s`:k, v]));
}

console.log(
 pluraliseKeys({
   name: "Tom",
   job: ["writing katas", "marking"],
   favouriteShop: [
     "Paul's Donkey University",
     "Shaq's Taxidermy Shack",
     "Sam's Pet Shop",
   ],
 })
);

CodePudding user response:

You're putting key "s" in the value of the key, not using it as a new key.

Instead of making a copy of the object and modifying it, make an empty object and copy they keys and values one at a time in the loop. Then you can add the s for the array values.

function pluraliseKeys(obj) {
  const newObj = {};
  for (const [key, value] of Object.entries(newObj)) {
    if (Array.isArray(value)) {
      console.log(key);
      newObj[key "s"] = value;
    } else {
      newObj[key] = value;
    }
  }

  return newObj;
}

  • Related