admin 管理员组

文章数量: 1086019

Lets say I have object:

{
  cart: 4,
  trolley: 10,
  car: 2,
}

How can I turn it into:

{
  shopping_cart: 4,
  shopping_trolley: 10,
  shopping_car: 2,
}

Lets say I have object:

{
  cart: 4,
  trolley: 10,
  car: 2,
}

How can I turn it into:

{
  shopping_cart: 4,
  shopping_trolley: 10,
  shopping_car: 2,
}
Share Improve this question asked Jul 5, 2022 at 18:17 AlyonaAlyona 1,8023 gold badges25 silver badges54 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

You can get the keys of the object in an array using the Object.keys() method. You can then use the Array.reduce() method to iterate over each of the keys and create a new object with desired prefix.

let obj = {
  cart: 4,
  trolley: 10,
  car: 2,
};

let pre = `shopping_`;

let nObj = Object.keys(obj).reduce((a, c) => (a[`${pre}${c}`] = obj[c], a), {});

console.log(nObj)

What have you tried so far?

var obj = {
  cart: 4,
  trolley: 10,
  car: 2
}

for (var key in obj) {
  obj["shopping_" + key] = obj[key]
  delete obj[key]
}

console.log(obj)

const createPrefixObjectKeys => prefix => source => {
  const prefixedSourceTuples = Object.entries(source).map(
    ([key, value]) => [
      `${prefix}${key}`,
       value
     ]
  );

  return Object.fromEntries(prefixedSourceTuples);
}

// use
const prefixObjectShopping = createPrefixObjectKeys('shopping_');

// where x is your object
const prefixed = prefixObjectShopping(x);

If you want to add keys even to nested objects in object. Use this (propably the easiest method)

function addKeyPrefixes(object, prefix){
    return JSON.parse(
        JSON.stringify(object).replace(/(?<=[{,]{1}\s*")(.+?)(?="\s*:)/gim, `${prefix}$1`)
    )
}

let obj = {
  'a' : {
    'b': 'c'
  },
  'd': 4
}

console.log(addKeyPrefixes(obj, '_'))

// {
//   '_a': {
//     '_b': 'c'
//   },
//   '_d': 4
// }

本文标签: How to add prefix to object keys in javascriptStack Overflow