1

Could someone tell me why particular key value getting repeat in object?

I've data like below getting from response like below.

var data = {
      "sub": {
        "LoadTime on linkedShip": "01:25:00 AM",
        "business Limit": "300",
        "avoid goods": "50",
        "avoid goods_Group": "100",
        "isPermanent": "['permLinkAccount']",
        "transport Limit": "1",
        "hasDailySlot": "1"
      }
    };
    

trying to replace "isPermanent": "['permLinkAccount']" to "isPermanent":"permLinkAccount" without changing other stuffs in object.

if (data.sub.hasOwnProperty("isPermanent")) {
  
  data = JSON.parse(JSON.stringify(data).replace(/[\[\]']/g,"permLinkAccount"));
  console.log('data', data);
}

but getting like isPermanent: "permLinkAccountpermLinkAccountpermLinkAccountpermLinkAccountpermLinkAccount" instead of "isPermanent":"permLinkAccount"

I need like

    LoadTime on linkedShip: "01:25:00 AM"
    avoid goods: "50"
    avoid goods_Group: "100"
    business Limit: "300"
    hasDailySlot: "1"
    isPermanent: "permLinkAccount"
    transport Limit: "1"

fiddle is here

What is wrong here?

2 Answers 2

2

Per your regex you are replacing [, ', and ] with permalinkAccount (hence the result) where you want to actually filter them out of the expression.

Just use and empty string as a replacement instead.

console.log("['permLinkAccount']".replace(/[\[\]']/g, ""))

Or

console.log("['permLinkAccount']".replace(/\W/g, ""))
Sign up to request clarification or add additional context in comments.

Comments

1

Try just parsing the JSON into an object and work with the object, it's easier.

const dataObj = JSON.parse(data);
if (dataObj.hasOwnProperty("isPermanent")) {
  dataObj.isPermanent = "permLinkAccount"
}

2 Comments

I think the idea is the OP doesn't know what the value of "permLinkAccount" is ahead of time...
@Gabriel Lupu this one so easy

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.