Home > front end >  Rename all keys in an object
Rename all keys in an object

Time:03-24

I'm trying to rename all the keys in an object to a new and different key which is value but all solutions I found on the internet show how to add a prefix to an existing key thus renaming it.

I have the following implementation

const shippingOption = {
  "": "Automatic",
  "ES_CartasNacionalesDeMas20": "Correos: cartas ordinarias, 2-4 Days",
  "ES_CorreosCartasCertificadas": "Correos: cartas certificadas, 2-4 Days",
  "ES_CorreosCartasCertificadasUrgentes": "Correos: cartas certificadas urgentes, 1-2 Days",
  "ES_CorreosChronoexpres": "Correos Express / Paq 24, 1 Day",
  "ES_CorreosPaq48": "Correos: Paq Premium, 2 Days",
  "ES_CorreosPaq72": "Correos: Paq Estándar, 2-3 Days",
  "ES_EconomyDeliveryFromAbroad": "Envío económico desde el extranjero, 10-22 Days",
  "ES_EconomyShippingFromGC": "Envìo economico desde China/Hong Kong/Taiwan to worldwide, 11-35 Days",
  "ES_EconomySppedPAK": "Envìo SpeedPAK economico desde China/Hong Kong/Taiwan, 10-15 Days",
  "ES_ENTREGA_KIALA_8KG": "Entrega a un punto Kiala (hasta 8 kg), 2-4 Days",
  "ES_EntregaConInstalacion": "Entrega con instalación (ver detalles), 3-5 Days",
  "ES_EntregaEnElPortal": "Entrega en el portal (ver detalles), 3-5 Days",
  "ES_EntregaEnNacexShop": "Entrega en NACEX.shop, 1-2 Days",
  "ES_EnvioEstandarAIslasBalearesCeutaMelilla": "Envío estándar a Ceuta/Melilla, 3-7 Days",
  "ES_EnvioEstandarALasIslasCanarias": "Envío estándar a las islas Canarias, 3-7 Days"
}

let renamed = Object.entries(shippingOption).reduce((acc, [k, v]) => {
  return { ...acc,
    [`value[${k}]`]: v
  };
}, {})

console.log(renamed)

Expected results

 const shippingOption = {

"value": "Automatic",
"value": "Correos: cartas ordinarias, 2-4 Days",
 "value": "Correos: cartas certificadas, 2-4 Days",
 "value": "Correos: cartas certificadas urgentes, 1-2 Days"
}

I want every key in the object to be renamed to value How can I do this?

CodePudding user response:

Your reducer should just use v instead of k if you want to name using the value of each property:

let renamed = Object.entries(shippingOption).reduce(
    (acc, [k, v]) => {
      return { ...acc, [`value[${v}]`]: v};
    },
    {},
);

CodePudding user response:

You can use mapped types and string literal to type the result of this operation:

type ValueKey<K extends string> = `value[${K}]`
type ConvertToValueKeys<T> = {} & { [K in keyof T & string as ValueKey<K>]: T[K] }
let renamed= Object.entries(shippingOption).reduce((acc, [k, v]) => {
    return { ...acc, [`value[${k}]`]: v};
}, {} as ConvertToValueKeys<typeof shippingOption>)

renamed["value[ES_CartasNacionalesDeMas20]"] // ok 
renamed["value[ES_CartasNacionalesDeMas210]"] // err

Playground Link

  • Related