JavaScript - Transform an object into an array object

Can anyone help me with converting the object retrieved from an API response into an array object? Here is the original object:

const oldObj = {
    Georgia : {
        notes: "lorem ipsum",
        lat: "32.1656",
        long: "82.9001"
    },
    Alabama : {
        notes: "lorem ipsum",
        lat: "32.3182",
        long: "86.9023"
    }
}

I want to transform it into the following array format:

const desireArray = [
    {
        name: "Georgia",
        notes: "lorem ipsum",
        lat: "32.1656",
        long: "82.9001"
    },
    {
        name: "Alabama",
        notes: "lorem ipsum",
        lat: "32.3182",
        long: "86.9023"
    }
];

I tried using forEach but encountered an error. Can someone provide assistance?

TypeError: oldObj.forEach is not a function

Any suggestions on how to achieve this transformation?

Answer №1

forEach is a method used for arrays, but in this case your oldObj is an object

To work with it as an array, you need to transform the object into an array of key-value pairs

Using map can help simplify the code

const oldObj = {
  Georgia: {
    notes: "Lorem ipsum",
    lat: "32.1656",
    long: "82.9001",
  },
  Alabama: {
    notes: "Lorem ipsum",
    lat: "32.3182",
    long: "86.9023",
  },
}

const res = Object.entries(oldObj).map(([name, obj]) => ({ name, ...obj }))

console.log(res)

References

Object.entries()

Answer №2

  1. To start, utilize the Object.entries method to locate the entries.
  2. Next, employ destructuring when reducing the current object by including the key in the accumulator.
  3. Lastly, add the modified object into the result array.

const oldObj = {
    Georgia : {
        notes: "lorem ipsum",
        lat: "32.1656",
        long: "82.9001"
    },
    Alabama : {
        notes: "lorem ipsum",
        lat: "32.3182",
        long: "86.9023"
    }
};

const result = Object.entries(oldObj).reduce((acc, curr) => {
    const [key, val] = curr;
    
    acc.push({
        name: key,
        ...val
    });
    return acc;
}, []);

console.log(result);

Answer №3

const oldObj = {
    Florida : {
        notes: "lorem ipsum",
        lat: "27.994402",
        long: "-81.760254"
    },
    Texas : {
        notes: "lorem ipsum dolor sit amet",
        lat: "31.9686",
        long: "-99.9018"
    }
}

const updatedArray = Object.keys(oldObj).map((key) => ({ place: key, ...oldObj[key] }));

Decipher the code above

const keys = Object.keys(oldObj);
const updatedArray = keys.map((key) => {
    return {
        place: key,
        notes: oldObj[key].notes,
        lat: oldObj[key].lat,
        long: oldObj[key].long
    }
});

Answer №4

const originalObject = {
    California : {
        notes: "lorem ipsum",
        lat: "36.7783",
        long: "119.4179"
    },
    Texas : {
        notes: "lorem ipsum",
        lat: "31.9686",
        long: "99.9018"
    }
};

function transformObjToArray(obj) {
  let result = [];
  for(let key in obj) {
    result.push({name: key, ...obj[key]});
  }
  return result;
}

console.log(transformObjToArray(originalObject));

or explore alternative solutions

 return Object.keys(obj).map(item => ( {name: item, ...obj[item]} ));

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

Angular, display the chosen option within the text input field

Currently, I have a table with multiple columns and I am using Angular JS to display their values in various controls. For instance, I am using a Select/Option (multiple) to display column A, and I want to use another text box to display column B based on ...

execute an action in the controller with the help of JavaScript and refresh the view

My scenario involves having multiple selects such as brands and products. I aim to dynamically update the products options based on the brand selected by the user. The select element looks like this: <select asp-for="Product.BrandId" class=&qu ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Inventory of distinct items with swift insert and remove capabilities

Currently, I am working on implementing a subscriptions list in node.js and have created the following object: var SubReq = function(topic, address, port){ this.topic = topic, this.address = address, this.port = port } var Subscribers = []; In orde ...

Maximizing the effectiveness of utilizing the include function for displaying various external pages within a single <div> element

Would it be more efficient to utilize the include method for displaying various external pages within a single <div>? When I say "more efficient," I am referring to the speed of loading the pages and its effectiveness compared to using ajax and javas ...

What is the best way to extract value from a JSON object with jQuery?

How can I retrieve the value of 'FRI' from the JSON feed returned by an AJAX call using jQuery? $.ajax({ url: query, type: "GET", dataType: "json" success: function(data) { var day = // extract data value from JSON ...

Dynamically insert JavaScript and CSS files into the header by using the append method

Due to a specific reason, I am loading CSS and scripts into my head tag using the "append" method. For example: $("head").append('<script type="application/javascript" src="core/js/main.js"></script>'); I'm asynchronously pulli ...

The Child Component in React Native Always Shows Undefined Response Status from API

In the code snippet below, I am facing an issue where the status returned by an API call is always showing as undefined in the child component, even though I can see the expected status code when logging it in the parent component. It seems like the child ...

Reorganizing elements within an array using a foreach loop

Currently, I am tackling the Facebook Graph API, which provides me with a JSON array response. However, I find myself needing to reformat the JSON as I am not entirely comfortable with their format. Here is an example of my JSON response: "ids": [ { ...

Having trouble accessing properties of an undefined object when trying to read 'credentials' in Firebase Auth within ReactJS

I need to verify the user's password again before allowing them to change it. Currently, my Firebase Auth setup is defined in Firebase.js and exported correctly //appConfig = ...(all the configurations here) const app = firebase.initializeApp(appConf ...

Encountering an issue with the removal of slides when updating JSON data for angular-flexslider

Issue: Although my JSON object is updating, the slider does not update for all resorts as expected. Sometimes it fails to update when the JSON object changes. The resorts (image collections) that do not update are throwing an error stating "cannot read pr ...

Run a script on a specific div element exclusively

Up until this point, we have been using Iframe to load HTML and script in order to display the form to the user. Now, we are looking to transition from Iframe to DIV, but we are encountering an issue with the script. With Iframe, the loaded script is onl ...

Tips for making my modal function properly?

I've encountered an issue with adding two modals to my website. The first modal works perfectly fine, but the second one is not functioning as expected. When I click on the button for the second modal, the background dims as it should, but the modal i ...

What could be causing my Django Slick-Slider carousel to malfunction?

I have encountered numerous posts discussing the same issue, but unfortunately, none of them offered a solution that worked for me. The slick-slider folder is properly stored in my static files and is being accessed correctly, yet no changes are reflected ...

In need of clarification on the topic of promises and async/await

I have been utilizing Promises and async/await in my code, and it seems like they are quite similar. Typically, I would wrap my promise and return it as needed. function someFetchThatTakesTime(){ // Converting the request into a Promise. return new ...

What could possibly be the issue with this mongoose query?

const images = await tbl .find({ creator_id: req.user._id, }) .select({ creator_id: 0, }) .then((images) => images.forEach((image) => { image.file_name = process.env.IMAGE_HOST_URL + ima ...

getting a null response when using the map feature - coding battles

Given an array filled with integers, my goal is to generate a new array containing the averages of each integer and its following number. I attempted to achieve this using the map function. var arr = [1,2,3,4]; arr.map(function(a, b){ return (a + b / ...

What is the best method for rounding a decimal number to two decimal places?

Here is the JavaScript code I am using: $("input[name='AuthorizedAmount'], input[name='LessLaborToDate']").change(function () { var sum = parseFloat($("input[name='AuthorizedAmount']").val()).toFixed( ...

Creating a JSON array in JavaScript for future reference

I am interested in creating a JSON array where I can define the fields and add data to it later in my code. However, I am unsure about the correct syntax to achieve this. So far, my attempts have resulted in some parse errors; <script> var myJSONAr ...

What is the best way to implement React.memo or useMemo and ensure semantic guarantees?

According to the documentation provided for useMemo: While useMemo can improve performance, it should not be solely relied upon for semantic guarantees. React may choose to recalculate previously memoized values in the future, such as to free up memo ...