0

I have a javascript object as follows:

result = [
   {"Account_ID__r.Name":"Yahoo Inc Taiwan","Contact_ID__r.Email":"[email protected]"},
   {"Account_ID__r.Name":"WXIA-TV","Contact_ID__r.Email":"[email protected]"}
]

I need to remove the period(.) from the keys of the object. (Example: The key Account_ID__r.Name should become Account_ID__rName)

The above array should become as follows:

result = [
   {"Account_ID__rName":"Yahoo Inc Taiwan","Contact_ID__rEmail":"[email protected]"},
   {"Account_ID__rName":"WXIA-TV","Contact_ID__rEmail":"[email protected]"}
]

I tried to construct a new array by using for (var key of Object.keys(result)) { } but it didn't work.

Code that I tried:

result.forEach(item => {
                    for (var key of Object.keys(item)) {
                        var keyWithoutPeriod = key.replace(/\./g,'');
                        this.datatableData.push({
                            [keyWithoutPeriod]: item[key] 
                        });
                    }
                });

It converted the code as follows:

datatable = [
   {"Account_ID__rName":"Yahoo Inc Taiwan"},{"Contact_ID__rEmail":"[email protected]"},
   {"Account_ID__rName":"WXIA-TV"},{"Contact_ID__rEmail":"[email protected]"}
]

This is not in the format that I need. Please help. Thank You😃.

1
  • 1
    In your code, replace this.datatableData.push() line with item[keyWithoutPeriod] = item[key]; delete item[key] Commented Sep 15, 2020 at 11:30

1 Answer 1

1

You could get entries, replace unwanted characters and build new objects.

const
    data = [
        { "Account_ID__r.Name": "Yahoo Inc Taiwan", "Contact_ID__r.Email": "[email protected]" },
        { "Account_ID__r.Name": "WXIA-TV", "Contact_ID__r.Email": "[email protected]" }
    ],
    result = data.map(o => Object.fromEntries(Object.entries(o).map(([k, v]) => [k.replace(/\./, ''), v])));

console.log(result);

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.