Transform every key and value into an array

How can I separate each key and value into individual arrays?

Here is the current data:

var inputArray = {
  "3/10/2017": 52,
  "3/11/2017": 58,
  "3/12/2017": 70,
  "3/13/2017": 76
}

The desired output should be:

var outputArray = [
  ["3/10/2017", 52],
  ["3/11/2017", 58],
  ["3/12/2017", 70],
  ["3/13/2017", 76]
]

Thank you!

Answer №1

["3/13/2017": 76] seems to be an invalid array syntax, however, you can correct it by replacing the colon : with a comma , or consider adding it as an object in each array.

var arr = {
  "3/10/2017": 52,
  "3/11/2017": 58,
  "3/12/2017": 70,
  "3/13/2017": 76
},
res = Object.keys(arr).map(v => new Array(v, arr[v])),
res2 = Object.keys(arr).map(v => new Array({[v]: arr[v]}));

console.log(JSON.stringify(res, 2, null));
console.log(JSON.stringify(res2, 2, null));

Answer №2

Utilizing Object.entries method

let data = {
  "5/10/2018": 43,
  "5/11/2018": 55,
  "5/12/2018": 68,
  "5/13/2018": 72
};

data = Object.entries(data);
console.log(JSON.stringify(data));

Answer №3

To extract key-value pairs from an object in JavaScript, you can utilize the map method along with Object.keys(). The map method takes a callback function as an argument, which is then applied to each item within the array.

var myObj = {
  "3/10/2017": 52,
  "3/11/2017": 58,
  "3/12/2017": 70,
  "3/13/2017": 76
};
console.log(Object.keys(myObj).map(function(key){
    return [key, myObj[key]];
}));

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

Exploring the depths of Vue.js: Maximizing potential with nested

In my Grid component, I retrieve JSON data from a server and render it. The data mainly consists of strings and integers, but sometimes includes HTML elements like <strong>myvalue</stong>. In order to properly display the data, I use triple bra ...

Husky and lint-staged failing to run on Windows due to 'command not found' error

I'm facing issues with getting husky and lint-staged to function properly on my Windows 10 system. Here's how my setup looks like: .huskyrc.json { "hooks": { "pre-commit": "lint-staged" } } .lintstagedrc ( ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

If I use npm install to update my packages, could that cause any conflicts with the code on the remote server?

As I navigate through the numerous issues, I stumbled upon the command npm ci that is supposed to not change the package-lock.json file. However, when I attempt to run npm ci, it fails: ERR! cipm can only install packages when your package.json and package ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...

Unravel the base64 encoded message from JavaScript and process it in Python

I'm currently facing an issue in Python while trying to decode a string sent by jQuery. Although I am not encountering any errors, I receive an encoding error when attempting to open the file. My objective is to decode the string in order to save it ...

JavaScript function to substitute instead of writing

function replaceHTML(a,b) { var x = document.getElementById("canvas_html").contentDocument; x.innerHTML = b; } Although the current function works fine, I would like to update it to directly replace the existing content instead of writing new con ...

Challenges encountered when attempting to access files from the filesystem on vercel

Currently, I am working on a website that includes a "blog" section with markdown files. The setup reads the files seamlessly from the file system without any errors... except when deployed on Vercel. In that case, it throws a "No such file or directory" e ...

Encountering problem with rendering the header in the footer within a customized package built on react

I am currently working on creating a node package that consists of simple HTML elements. The package is named fmg_test_header. These are the files included in the package: header.jsx index.js package.json header.js function Header() { return "< ...

Trouble with CSS animation when incorporating JavaScript variables from a PHP array

Whenever I use a script to fetch an array of objects from PHP... I successfully display the results on my website by outputting them into Divs. The challenge arises when I introduce CSS animations. The animation only triggers if the variable length excee ...

The array is acting strangely and not functioning as expected

I am currently working with express, node, and mongoose. When I access my mongoDB database and log it to the console, I get the following array: module.exports ={ stories: function(req, res, next){ Story.find(function(err, stories){ if(err) ...

Issue with defining an array of JTextAreas

Every time I try to declare an array of JTextAreas using this line of code: tabs[i] = new javax.swing.JTextArea(); I keep running into the same issue: java.lang.NullPointerException The tabs variable is defined like this outside of the procedure whe ...

Creating dynamic components in Vue.js using VueJS and jQuery synergistically

New to Vue.js and in the process of building a Vue component inspired by this custom select menu. I want to include an ionicon with each list item. Typically, I can add the icon in Vue.js using: <component class="icon" :is="name-of-icon& ...

Error: Failed to find the location because geolocate has not been defined

I searched extensively online for a solution to my problem without success, so I am reaching out to seek your assistance. I am attempting to utilize the Google Address auto-complete API within an asp.net core framework. In my razor file, I have included: ...

Summoning within a rigorous mode

I am facing an issue with my configuration object: jwtOptionsProvider.config({ tokenGetter: (store) => { return store.get('token'); }, whiteListedDomains: ['localhost'] }); In strict mode, I ...

The error occurring in the React app is a result of the page rendering prior to the API data being fetched

Utilizing the following component for my Nav, I aim to showcase the current weather based on the user's location. However, an issue arises as the page is being rendered before retrieving data from the openWeather API. import React, { useState, useEffe ...

The RxJs Observer connected to a websocket only triggers for a single subscriber

Currently, I am encapsulating a websocket within an RxJS observable in the following manner: this.wsObserver = Observable.create(observer=>{ this.websocket.onmessage = (evt) => { console.info("ws.onmessage: " + evt); ...

Problem with detecting collisions in Three.js

Currently, I am developing a simple game where players can add objects (cubes) to the scene at the position of a raycaster (mouse) click on a large ground plane. To prevent cubes from overlapping with each other, I have implemented basic collision detectio ...

Getting an input value dynamically in a React variable when there is a change in the input field

I am having an issue with my search text box. I need to extract the value onchange and send a request to an API, but when I try using the normal event.target method, it shows an error. How can I fix this? The problem is that onchange, I need to call a func ...

Is there a way to customize the checkout page using JavaScript?

I'm working on a checkout page where fields need to change based on a selected radio button. There are two options: A and B. When A is selected, I want certain fields to remain visible while others disappear, and vice versa for option B. Although I p ...