How can you change an array of objects into an array of arrays?

Here we have a JSON object structured like this:

var items = [{
    title: 'example 1',
    image: 'http://www.lorempixel.com/700/600/'
}, {
    title: 'example 2',
    image: 'http://www.lorempixel.com/900/1200/'
}, {
    title: 'example 3',
    image: 'http://www.lorempixel.com/400/300/'
}, {
    title: 'example 4',
    image: 'http://www.lorempixel.com/600/600/'
}, {
    title: 'example 5',
    image: 'http://www.lorempixel.com/400/310/'
}, {
    title: 'example 6',
    image: 'http://www.lorempixel.com/410/300/'
}, {
    title: 'example 7',
    image: 'http://www.lorempixel.com/500/300/'
}, {
    title: 'example 8',
    image: 'http://www.lorempixel.com/300/300/'
}, {
    title: 'example 9',
    image: 'http://www.lorempixel.com/450/320/'
}, {
    title: 'example 10',
    image: 'http://www.lorempixel.com/500/400/'
}];

The goal is to create an array in the following format:

[['example 1', 'http://www.lorempixel.com/700/600/'], ['example 2', 'http://www.lorempixel.com/900/1200/'], ....]

Initially, an attempt was made in the code snippet below:

const rows = [];
            for (let i = 0; i < items.length; i++) {
                const element = items[i];
                rows[i] = element.title;
                for (let j = i; j < items.image; j++) {
                    const el = response[j];
                    rows[j] = el.image;
                }
            }

However, this resulted in only images being stored in the array due to overriding values during the second loop. What would be the correct approach to retrieve both values as intended?

Answer №1

To utilize Object.values() as a callback function for .map(), simply follow this example:

let items = [
  {name: 'item 1', price: '$50'},
  {name: 'item 2', price: '$30'},
  {name: 'item 3', price: '$20'},
  {name: 'item 4', price: '$40'}
];

let output = items.map(Object.values);

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

Answer №2

Simply use the .map function to extract the necessary property values from the object and create an array with those values:

var items=[{title:'sample 1',image:'http://www.lorempixel.com/700/600/'},{title:'sample 2',image:'http://www.lorempixel.com/900/1200/'},{title:'sample 3',image:'http://www.lorempixel.com/400/300/'},{title:'sample 4',image:'http://www.lorempixel.com/600/600/'},{title:'sample 5',image:'http://www.lorempixel.com/400/310/'},{title:'sample 6',image:'http://www.lorempixel.com/410/300/'},{title:'sample 7',image:'http://www.lorempixel.com/500/300/'},{title:'sample 8',image:'http://www.lorempixel.com/300/300/'},{title:'sample 9',image:'http://www.lorempixel.com/450/320/'},{title:'sample 10',image:'http://www.lorempixel.com/500/400/'}];

console.log(
  items.map(({ title, image }) => [title, image])
);

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

Using Javascript to send a post request and handle multiple responses

Is it possible to receive multiple responses from the server? When making a post request, my code only seems to capture the first response from the server. How can I ensure that all three responses are captured and processed? Below is the index.html page ...

Facing issues with ReactCSSTransitionGroup as transitionAppear feature is not functioning

I'm having trouble with the appearance and disappearance of notifications. The transitionAppear property doesn't seem to be working as expected. I'm adding the notification popup item to the onBlur event. The animation for the leave event wo ...

The function upgradeDom() from vue mdl componentHandler is not returning a valid function

Attempting to integrate mdl into a vue.js project (using vue v2.1) and encountering a familiar issue to that discussed here. However, when I include mounted () { componentHandler.upgradeDom()} in my App.vue, I am receiving the following error: TypeError: ...

How can I implement a 2D array with dynamic sizing in a C++ class?

Currently, I am exploring the realm of classes in C++ (traditionally, I work with Python) and encountering some unexpected outcomes while experimenting with a dynamically resizing version of Tic Tac Toe game. Here's the code snippet: #include <ios ...

Retrieve data from a div element on a webpage using specific parameters

As I work on a form that includes various filters and a "Start" button in C# / ASP.NET MVC, my goal is to display database data in a partial view using Ajax when the button is clicked, based on certain parameters. Within this partial view, there is a link ...

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

What is the best way to extract ABC 12005 from strings like ABC000012005 and ABC0000012005?

My task involves parsing a string with values like ABC000012005,ABC0000012005. The desired output is to extract the prefix and numbers without leading zeros, formatted as ABC 12005, ABC 12005 ...

Utilizing the nested combination of map and filter functions

Struggling to grasp the concept of functional programming in JavaScript, my aim is to extract object boxart items with width=150 and height=200. Console.log(arr) the output shows [ [ [ [Object] ], [ [Object] ] ], [ [ [Object] ], [ [Object] ] ] ] I&apos ...

Upon implementing a catch-all express routing solution, the Fetch API calls are no longer successful. The error message received is "Unexpected token < in JSON at

While working on a React project, I encountered an issue outlined in this link: React-router urls don't work when refreshing or manually typing. To resolve this problem, I decided to implement the "Catch-All" solution recommended in that discussion. ...

What is the best way to simulate a constructor-created class instance in jest?

Suppose there is a class called Person which creates an instance of another class named Logger. How can we ensure that the method of Logger is being called when an instance of Person is created, as shown in the example below? // Logger.ts export default cl ...

What is the best way to insert an object into an array after every third object?

Imagine having an array ranging from 0 to 100. let array = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"...."100"] Now, the task at hand is to insert "-" after every set of 3 elements in the array. The desired output should look like this: array = ...

Having trouble loading a static image using the [email protected] component via webpack

I am struggling to display a static image in my component called Top.js. To import the image, I have used the following code in Top.js: import logo from './images/logo.png' The path for logo.png is frontend/src/images/logo.png. Next, I tried ...

Utilizing Functions for Displaying Data (Arrays and Iterations)

public class DataSecurity { private static final int[] encrypt = {2, 9, 3, 4, 6, 8, 1, 0}; private static final int[] decrypt = new int[8]; private static final int minLength = 10; String secureEncryption (String data) { if(data.length()<minLeng ...

I am having trouble retrieving any data when using jQuery to post JSON data

I am struggling with some HTML and JavaScript code. Here is what I have: <html> <head> </head> <body> <script src="view/backoffice/assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></sc ...

In case of an API error with the Nuxt fetch method, ensure that the entire site responds with a 404

Is it possible to configure a Nuxt website to respond with a 404 error when the API raises a 404 error? The API call is made on the client side using the fetch method: Check out this demo here: codesandbox demo Code Snippets index.vue <template> ...

If an element exists in one of the dimensions of a multi-dimensional array

I am facing an issue with my 2D array structure. Here is an example of how it looks: `var arr = [["1", "2", "3"], ["4", "5"], ["6"]];' Despite having the value "4" in one of the inner arrays, when I try running $.inArray("4", arr); or arr.indexOf("4" ...

What is causing the anchors in my submenu to not function properly?

I'm currently working on a jQuery dropdown script for my navigation submenus. I have managed to implement the functionality of adding chevrons to the top-level links that have submenus, but I've encountered an issue where the 'return false&a ...

The V-model seems to be failing to bind to the DOM element

I'm encountering an issue with the code I've written. The v-model is not binding the data in the DOM, even though the axios I'm using is returning values. Here is the code snippet: <template> <v-container fluid> <v-layo ...

When using axios to post to an API, the data being sent is showing as an empty object when logged on the server

I recently started working with nodejs and have been experimenting with sending data in a post API using axios, but I am encountering an issue where the data is not being received on the server side. Here is my current setup: CLIENT export default class A ...

Understanding the Execution of Asynchronous Code

I've been grappling with this problem for a while now, but I just can't seem to find the solution. That's why I'm reaching out for your expertise. Consider the example below: const async = require('async') var counter = 0 v ...