Changing a collection of values in an object into a designated array shape

I have an object with the following values:

const data = {
    "generalInfo": [{
            "title": "title1",
            "permalink": "www.link.com",
            "manufacturer": "manufacturer1",
            "category": [{
                "term_id": 35,
                "name": "Motherboard",
                "slug": "motherboard"
            }],
            "img": "https://images-na.ssl-images-test.com/images/asdfIdR/5adf1vELadfZeiMML.jpg",
            "curreny": "$",
            "price": "64.00",
            "availability": "Usually ships in 24 hours",
        },
        {
            "title": "title2",
            "permalink": "www.link.com",
            "manufacturer": "manufacturer2",
            "category": [{
                "term_id": 35,
                "name": "Motherboard",
                "slug": "motherboard"
            }],
            "img": "https://images-na.ssl-images-test.com/images/I/51adfkLhadsfgACH0L.jpg",
            "curreny": "$",
            "price": "59.99",
            "availability": "Usually ships in 24 hours",
        }
    ]
}

// console.log(typeof(data))

var vals = Object.keys(data).map(function(key) {
    return data[key]
})

console.log(vals)

// expected output
// [ "1", "title1", "manufacturer1", "64.00", "Usually ships in 24 hours", "", "" ],
// [ "2", "title2", "manufacturer2", "59.99", "Usually ships in 24 hours", "", "" ],

I am attempting to utilize Object.keys(data).map to form an array structure from my object. However, I am getting an array nested within another array containing 2 objects. But, I am aiming for the desired output shown below:

// expected output
// [ "1", "title1", "manufacturer1", "64.00", "Usually ships in 24 hours", "", "" ],
// [ "2", "title2", "manufacturer2", "59.99", "Usually ships in 24 hours", "", "" ],

If you have any suggestions on how to transform the array to achieve the above results, please let me know.

Your input is greatly appreciated!

Answer №1

What you desire is not related to the use of Object.keys. Utilize map directly on the generalInfo key:

const info = {"generalInfo":[{"title":"title1","permalink":"www.link.com","manufacturer":"manufacturer1","category":[{"term_id":35,"name":"Motherboard","slug":"motherboard"}],"img":"https://images-na.ssl-images-test.com/images/asdfIdR/5adf1vELadfZeiMML.jpg","curreny":"$","price":"64.00","availability":"Usually ships in 24 hours"},{"title":"title2","permalink":"www.link.com","manufacturer":"manufacturer2","category":[{"term_id":35,"name":"Motherboard","slug":"motherboard"}],"img":"https://images-na.ssl-images-test.com/images/I/51adfkLhadsfgACH0L.jpg","curreny":"$","price":"59.99","availability":"Usually ships in 24 hours"}]};
let values = info.generalInfo.map((element, index) => [index + 1, element.title, element.manufacturer])
console.log(values);

I am uncertain about the significance of the last two values, hence they have been excluded. You can add them similarly as shown above.

Answer №2

It is recommended to utilize Object.values() in place of Object.keys() when extracting the values of each object within data.generalInfo and organizing them into a new array format:

const data = {
    "generalInfo": [{
            "title": "title1",
            "permalink": "www.link.com",
            "manufacturer": "manufacturer1",
            "category": [{
                "term_id": 35,
                "name": "Motherboard",
                "slug": "motherboard"
            }],
            "img": "https://images-na.ssl-images-test.com/images/asdfIdR/5adf1vELadfZeiMML.jpg",
            "curreny": "$",
            "price": "64.00",
            "availability": "Usually ships in 24 hours",
        },
        {
            "title": "title2",
            "permalink": "www.link.com",
            "manufacturer": "manufacturer2",
            "category": [{
                "term_id": 35,
                "name": "Motherboard",
                "slug": "motherboard"
            }],
            "img": "https://images-na.ssl-images-test.com/images/I/51adfkLhadsfgACH0L.jpg",
            "curreny": "$",
            "price": "59.99",
            "availability": "Usually ships in 24 hours",
        }
    ]
}

// console.log(typeof(data))

var vals = data.generalInfo.map(function(obj) {
    return Object.values(obj);
})

console.log(vals)

// expected output
// [ "1", "title1", "manufacturer1", "64.00", "Usually ships in 24 hours", "", "" ],
// [ "2", "title2", "manufacturer2", "59.99", "Usually ships in 24 hours", "", "" ],

Answer №3

To specify the desired order of items, you can create an array of keys.

var data = { generalInfo: [{ title: "title1", permalink: "www.link.com", manufacturer: "manufacturer1", category: [{ term_id: 35, name: "Motherboard", slug: "motherboard" }], img: "https://images-na.ssl-images-test.com/images/asdfIdR/5adf1vELadfZeiMML.jpg", curreny: "$", price: "64.00", availability: "Usually ships in 24 hours" }, { title: "title2", permalink: "www.link.com", manufacturer: "manufacturer2", category: [{ term_id: 35, name: "Motherboard", slug: "motherboard" }], img: "https://images-na.ssl-images-test.com/images/I/51adfkLhadsfgACH0L.jpg", curreny: "$", price: "59.99", availability: "Usually ships in 24 hours" }] },
    keys = ['title', 'manufacturer', 'price', 'availability'],
    result = data.generalInfo.map((o, i) => [(i + 1).toString(), ...keys.map(k => o[k]), '', '']);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Implementing bind to invoke a function during an onClick Event

Here is a code snippet I have been working on that demonstrates how to handle click events on hyperlinks. The code features two hyperlinks named A and B. When hyperlink A is clicked, the console will log 'You selected A', and when B is clicked, ...

Having trouble constructing the Grand-Stack-Starter api because babel-node is not being recognized

As I endeavor to create the initial api for the Grand Stack Starter, I encounter difficulties every time I try to execute npm start: >nodemon --exec babel-node src/index.js [nodemon] 1.18.7 [nodemon] to restart at any time, enter `rs` [nodemon] watchi ...

Create your own custom block on the frontend product page

I am trying to create a custom block on the Product Page of my Magento store. I attempted it like this: Magento- How can i add a new custom block in product details page using module Unfortunately, it did not work as expected. Did I make any mistakes he ...

What are some strategies to prevent django form fields from being reset or cleared in the event of an error during submission?

I'm utilizing django's registration-redux for user registration, but I'm facing an issue. When I enter the same user ID, it displays an error and clears all the input fields on the form. How can I prevent this error from occurring without cl ...

Exploring JqueryUI tab navigation with the help of the <a> tag

I have come across several articles mentioning the possibility of navigating JqueryUI tabs using a button or anchor tag. Here is the method I am currently using: $("#vtabs").tabs(); $("#tabsinner").tabs(); $(".changeTab").click(function() { alert("as ...

How can you delay the return of a function until after another asynchronous call has finished executing?

Currently, I am working on implementing route authentication in my project. To achieve this, I have decided to store the authenticated status in a context so that other React components can check whether a user is logged in or not. Below is the relevant co ...

The contact form fields shimmer as they transition in and out

I am currently working on a contact form that includes four input fields - name, phone, email, and message. The functionality I am looking to implement is that when I click on one input field, the other fields will fade by 30%, such as email, phone, and ...

Encountering issues with styling the search bar using CSS and unable to see any changes reflected

I am currently working on creating a searchBar and customizing its CSS, but unfortunately, most of the styling properties seem to not be taking effect. So far, only changing colors seems to work as expected. .mainBar{ background-color: blue; width: ...

Navigating through nested JSON arrays in JavaScript involves looping through multiple dimensions

I am facing difficulty finding the correct solution to my issue here. I am trying to iterate through the nested Products arrays in order to display each Product name. Can this be achieved with my current code, or should I consider rewriting it to make qu ...

Extract attributes from a string of HTML containing name-value pairs

Here is a sample string that I need to work with '<img id="1" data-name="test" src="img_01.jpg" />' My goal is to extract the attribute name and value pairs from the string, create the element, and apply these attributes. I have come up ...

Retrieving MySQLi results as an array using PHP and MySQL: a comprehensive guide

This code has been recently updated. However, an error was encountered: FATAL ERROR (Call to undefined method User::fetch_assoc()) The following is the method code: public function getAllUsers(User $user) { $stmt = $this->conn->prepare("SELEC ...

Leveraging JSON data in a client-side JavaScript script

Recently, I started exploring node.js and express. One issue that I am currently facing is how to correctly retrieve json data in a client-side javascript file. I keep receiving a 404 error indicating that the .json file cannot be found. In my project&apo ...

Obtain data from a local JSON file using the http.get() method in Angular 2

I am attempting to utilize the http.get() method in Angular 2 to load a local JSON file. I followed a suggestion from Stack Overflow that involves modifying my app.module.ts: In this example, I have imported the HttpModule and the JsonModule from @angular ...

Steps to launching a URL in a new window on Internet Explorer

I want it so that when button1 is clicked, the URL opens in a new window using Internet Explorer. ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

Guide on navigating through various HTML pages with distinct parameters using Node.js (Express server)

Seeking assistance with a Node.js server that receives an ID as a query parameter. Each time a client connects with different parameters, I aim to serve them a unique HTML page containing a simple UI with 2 dynamic arrays. Everything seems to be working co ...

Combine JavaScript array objects based on their unique IDs

Looking to combine 2 arrays of objects based on IDs (ID and AUTOMOBIL). However, the current code only saves the last array of objects (OPREMA). Any suggestions on how to merge all of them correctly? If the ID in a1 is == 1, I want to save all OPREMA wher ...

Learning how to dynamically update a value in Angular based on user input

My goal is to dynamically change the output value based on user input using Angular. I have successfully implemented the functionality to increment the value, but unfortunately, when the input changes, the outputed value remains static. Below is my curren ...

"Click here to access the downloadable content obtained through web scraping

I am looking to automate a task using Python where I need to get a PDF file from a website with fileid 8426 and date 03312021. Visit this link: Click on the "Download PDF" button Save the downloaded file to a directory After exploring, I came across a P ...