0

I've an object like this:

const obj = {a: {x: 0, y: 0}}

that could be also:

const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}}

So, the obj can have more than one key and with variables key names. I need to replace each x value with a a string like this ${x}% so the x value + the percentage symbol.

How can I do that?

The expected results should be:

const obj = {a: {x: 0, y: 0}} // {a: {x: '0%', y: 0}}
const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}} // {a: {x: '0%', y: 0}, b: {x: '10%', y: 3}, abcd: {x: '-1%', y: 0}}

I tried looping the object but I don't know if there is a smartest solution

3 Answers 3

1

const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}}

let result = Object.fromEntries(Object.entries(obj).map(([k,v]) => {
    return [k,{...v,x:`${v.x}%`}]
}))

console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

1

You can also check the object recursively. So no matter how deep the object goes every given key that matches gets a suffix.

I also make sure to create a copy of the object to prevent altering the original object(s).

const obj = {a: {x: 0, y: 0}, b: {x: 10, y: 3}, abcd: {x: -1, y: 0}};

const addSuffixToObj = (obj, key, suffix) => {
  const copy = {...obj};

  Object.keys(copy).forEach((prop) => {
    if (typeof copy[prop] === 'object') {
      copy[prop] = addSuffixToObj(copy[prop], key, suffix);
    }else if(prop === key){
      copy[prop] = copy[prop] + suffix;
    }
  });
  
  return copy;
}

// Add "%" to all "x" keys
const result = addSuffixToObj(obj, 'x', '%');

console.log(result);

Comments

0

You can get the array of object keys and then use forEach, it's a method that executes provided function for every element of array(here - for every object key):

Object.keys(obj).forEach(el => obj[el].x = `${obj[el].x}%`)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.