JavaScript - Replacing key/value pairs in an object and transferring them to a different object

I am struggling with accessing and modifying the keys, values, and entries in an object (array), then transferring it to a new empty object (newArray). While I can retrieve the keys, values & entries, I'm facing difficulty making changes to them.

The code below is functional, but I aim to generalize it for broader usage across different scenarios.

I have experimented with Object.keys(), Object.values(), Object.entries(), as well as keyof typeof x, yet haven't been successful as .replace() method doesn't work smoothly with objects.

The object is obtained as a CSV file where double quotes are used to separate fields due to potential commas disrupting the structure.

let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

let newArray = [];

array.forEach(s => {
    let x = JSON.parse(JSON.stringify(s)); 
    x.addressLine1 = x.addressLine1.replace(x.addressLine1, `"${x.addressLine1}"`);
    x.addressLine2 = x.addressLine2 ? x.addressLine2.replace(x.addressLine2, `"${x.addressLine2}"`) : '';
    x.town = x.town.replace(x.town, `"${x.town}"`);
    x.postcode = x.postcode.replace(x.postcode, `"${x.postcode}"`);
    newArray.push(x);
});

Attempt utilizing keyof typeof:

array.forEach(s => {
    let x = JSON.parse(JSON.stringify(s));
    let property: keyof typeof x;
    for (property in x) {
        property = property ? property.replace(property, `"${property}"`) : '';
        newArray.push(x);

Desired format of the object:

{
    "addressLine1": "\"The Road\"",
    "addressLine2": "",
    "town": "\"London\"",
    "postcode": "\"SE1 5QH\"",
}

Answer №1

One approach you could consider is avoiding the process of "stringifying" your objects and instead creating them directly from the object itself.

Here's an example to illustrate this concept (a working example can be found here): https://codesandbox.io/s/dark-dawn-w85z3

let objArray = [
  {
    addressLine1: "anothernamefieldexampleline1",
    addressLine2: "exampleline2",
    town: "exampletown1",
    postcode: "examplepostcode1"
  },
  {
    addressLine1: "exampleline1b",
    addressLine2: "exampleline2b",
    town: "exampletown1b",
    postcode: "examplepostcodeb"
  }
];
let array = typeof objArray != "object" ? JSON.parse(objArray) : objArray;

let newArray = array.map((_itemObject) => {

  let returnObject={};


  let arrayKeyProperties = [];
  for (const key in _itemObject) {
    arrayKeyProperties.push(key);
  };

  console.log(arrayKeyProperties);

  arrayKeyProperties.forEach(
    (_prop) => returnObject[_itemObject[_prop]] = _itemObject[_prop]
  );

  return returnObject;
});

console.log(newArray);

A visual representation of the output is shown, depicting the array created with new objects featuring updated field names based on the values of the old ones.

https://i.sstatic.net/Ax1de.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Unable to access unknown properties (reading 'extend')

Struggling to integrate the Vuetify library into my current Vue 3 project, encountering complications. An error message popped up post-compilation: vuetify.js?ce5b:42021 Uncaught TypeError: Cannot read properties of undefined (reading 'extend') ...

Ordering products in Angular JS based on whether they are free or not can be done by

I am currently implementing Angular's ng-repeat to showcase products from a JSON feed. My goal is to organize and categorize these products by distinguishing between free items (with the JSON property 'free':true) and those that require a pu ...

Tomickigrzegorz Script Finder Predictive Search

Hey there, I recently tried out the autocomplete script created by tomickigrzegorz. Check it out here! It's been working smoothly for me, but I'm facing an issue with external link tags like https//google.com not functioning properly. Here is ...

Once the Ionic platform is prepared, retrieve from the Angular factory

I have created a firebase Auth factory that looks like this: app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform", function($firebaseAuth, FIREBASE_URL, $ionicPlatform) { var auth = {}; $ionicPlatform.ready(function(){ ...

What are the reasons behind the issues encountered when enabling "Optimization" feature in Angular that affect the proper rendering of PrimeNg elements?

Angular Version : 9.x Primeng Version : 9.x We've encountered an issue with PrimeNg elements not rendering correctly in our dev/prod environments, although they work fine in the local environment. After some investigation, we found that the culprit ...

Create a Bar Graph Using a List

Looking to generate an Angular Barchart from a JPA query in Spring: public List<PaymentTransactionsDailyFacts> findPaymentTransactionsDailyFacts(LocalDateTime start_date, LocalDateTime end_date) { String hql = "SELECT SUM(amount) AS sum_volume, ...

Having trouble with a single GET request not functioning properly on Safari due to an Authorization issue in Angular 6

I've encountered this issue in several locations, yet haven't found a clear solution. Only one GET request is showing as unauthorized (401), but when I check the debugger, everything seems to be fine and all other requests are functioning properl ...

`JQuery fadeOut seems to have a limitation where it only applies to the

I have a group of divs, each containing an anchor tag that triggers a JavaScript function (which uses AJAX to delete a row from a table). Here's an example setup: <div id="container"> <div><a id="btn" onclick="deleteRow()">Delet ...

Tips for eliminating repeated values in a textbox

<script> $("#filter").on("shown.bs.popover",function(){ $(".popover-content input[type=checkbox]").on("click",function(){ if(this.checked) { this.setAttribute("checked","checked"); } else { ...

Is it possible to alter the input value dynamically before submitting the form or refreshing the

I am looking to automatically update a hidden input value to either "0" or "1" based on whether a user fills out the phone number field. My current code is below: <script> if(document.getElementById('user-tel').value!='') { docu ...

Exploring Javascript through Python using Selenium WebDriver

I am currently attempting to extract the advertisements from Ask.com, which are displayed within an iframe generated by a JavaScript script hosted by Google. Upon manually navigating and inspecting the source code, I can identify the specific element I&ap ...

Guide: Passing and reading command line arguments in React JavaScript using npm

When launching the react application, I utilize npm start which is defined in package.json as "start": "react-scripts start -o". Within the JavaScript code, I currently have: const backendUrl = 'hardCodedUrl'; My intention ...

An error was thrown due to an unexpected end of JSON input while fetching from localhost

After running the code snippet provided, I encountered an Uncaught SyntaxError: Unexpected end of JSON input. As a beginner in coding, any guidance or assistance would be greatly appreciated. Thank you. fetch('http://localhost:3000/add-user', { ...

Tips for utilizing the .clone() method within a loop or for each individual element of an array

Due to certain requirements, I find myself in a situation where I need to customize the invoice template within the software I use. The invoices are generated in HTML format, prompting me to consider utilizing Stylish and Grease Monkey for this task since ...

Using React to simulate API calls outside of testing environments

For instance, I encounter issues when certain endpoints are inaccessible or causing errors, but I still need to continue developing. An example scenario is with a function like UserService.getUsers where I want to use fake data that I can define myself. I ...

The $().bind function will not function properly unless the document is fully loaded

Do I need to include $(document).ready() with $().bind? Here is the HTML portion: <head> <script type="text/javascript" src="jquery-1.10.2.min.js"></script> <script type="text/javascript" src=&quo ...

Adding dynamic text to a <span> tag within a <p> element is causing a disruption in my layout

I'm encountering an issue with a Dialog box that displays a message to the user regarding file deletion. Here's how it looks: +-----------------------------------------------------------------------+ | Delete File? ...

Angular 2 destroy outlet-content and refresh the view

Is there a method in Angular 2 to remove a component that was automatically created within a router-outlet? I am looking to destroy it so that a new one is generated when I navigate back to that outlet (or is there a way to reload the outlet?). ...

Is there a way to generate an array from 1 to X without using a loop?

What is a way to generate a JavaScript array from 1 to X without using a loop when the value of X is only known at runtime? var arr = []; for (var i = 1; i <= x; i++) { arr.push(i); } ...

Generate a dynamic file import loop within a React application

Suppose I have a directory containing several .md files: /static/blog/ example_title.md another_example.md three_examples.md and an array that includes all the titles: const blogEntries = ["example_title", "another_example", "three_examples"] In ...