Tips for consuming a JSON object and generating two arrays in JavaScript

Is there a way to create two arrays from a JSON input, with one array containing only keys and the other containing only values, while excluding pairs where the key is numerically equal to the value?

Answer №1

To iterate over the key-value pairs of an object, you can utilize `Object.entries` and then sort them into separate arrays if the key and value are different. Here's a demonstration:

let obj = {a:5, b:6, c:3, '1':4,'2':2};
let keys = [] , values = [];
Object.entries(obj).forEach(([key,value])=> {
    if(key != value){
        keys.push(key);
        values.push(value)
    }
});

console.log('keys:',keys);
console.log('values:', values);

Answer №2

If my understanding is correct, there are two built-in functions that can provide you with the keys and values of an object without the need for looping.

  • Object.values retrieves all values of an object (mdn docs)
  • Object.keys retrieves all keys of an object (mdn docs)

These functions can be used with both Objects and Arrays:

var data = {x:1, y:2, z:3, '1':5,'2':'b'};
// visualization of input data
console.info('data-object:', JSON.stringify(data));
// retrieved keys
console.info('keys:',  Object.keys(data));
// retrieved values
console.info('values:',  Object.values(data));

var list = [5,6,7,8];
// visualization of input data
console.info('data-array:', JSON.stringify(list));
// retrieved keys
console.info('keys:',  Object.keys(list));
// retrieved values
console.info('values:',  Object.values(list));

var data2 = {"a":10, "b":20};
// visualization of input data
console.info('data-obj2:', JSON.stringify(data2));
// extracted keys
console.info('keys:',  Object.keys(data2));
// extracted values
console.info('values:',  Object.values(data2));

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

When an event occurs, have Express make an HTTP call to Angular

In the process of developing an Angular application, I am working on a feature that will enable around a thousand users to connect simultaneously in order to book tickets. However, I only want a specific number of them, let's call it "XYZ", to access ...

Grab all the text using Java Jsoup

I am having an issue with the code I have written. The doc.body.text() statement is not displaying the text content within the style and script tags. I examined the .text() function code and found that it searches for all instances of TextNode. Can someone ...

What is the best way to eliminate an object from an array using JavaScript?

I am currently working with two arrays named totalArray and selectionArray. These arrays have dynamic values, but for the sake of example I have provided sample arrays below. My goal is to remove objects from totalArray based on their id rather than inde ...

Develop a new object that holds an array of various other objects

I need assistance with creating a JSON object structure similar to the following: "datasets": [{ "label": "# of Votes", "data": [20, 10, 3], "backgroundColor": [ "#ccf9d6", ...

The Bootstrap Mobile Navigation transition is not displaying as intended in my CSS coding

On both desktop and mobile screen sizes, I have a white navigation bar. However, for the mobile dropdown menu, I want the background to be grey. I managed to achieve this by targeting .show on smaller screens in the CSS and specifying the grey background ...

Ensure that the query is properly separated from the body when making an Axios request

While working on my code, I encountered an issue when making a PUT request to the backend of the application using Axios. The problem arose when the method in the user service, responsible for handling the request, returned a null response. Here is the met ...

Error message encountered in AngularJS when trying to send Fullcalendar: TypeError - Cannot access property '__id' of an undefined object

Recently, I integrated angular-ui-calendar into my website. Within the controller, I implemented the following: define(['underscore'], function (_) { "use strict"; var SearchController = function ($scope, $location, OrdersService, U ...

Retrieving saved data from LocalStorage upon page reload

<div ng-repeat="section in filterSections"> <h4>{{ section.title }}</h4> <div class="checkbox" ng-click="loaderStart()" ng-if="section.control == 'checkbox'" ng-repeat="option in section.options"> <label ...

Tips for preventing the need to escape the /n character in every microservice within the chain using Java

Consider this scenario: we are receiving a json message from our partner in the following format: { "message": "Dear client,\nWe'd like to offer you.." } Our partner wants the client to receive the message without a newline c ...

The AJAX event is failing to send data

When using two ajax calls, the first one populates a dropdown box successfully. However, the second ajax call utilizes a change event function to list product details with images whenever a dynamically populated item from the dropdown is clicked. In the c ...

Enable users to input their custom code and run it when the specified conditions are met

Currently, I am developing a Multi-tenant application that requires users to input their own code and run it under specific conditions. I have several ideas in mind, but I am unsure which approach would be most effective. All the proposed methods will ha ...

Restrict the number of items in each list to just one

I'm trying to customize a query that displays a list of numbers. My goal is to only display each unique number once. For example, if there are three instances of the number 18 in the database, I want it to show as 18, 18, 18. If there are two occurre ...

Modifications made to the process module in one file are not reflected in a different file

It seems that the process module in NodeJS is not global, resulting in changes made to it in one module not reflecting in other modules. To confirm my findings, I wrote a small piece of code. Here is the snippet: server.js import app from "./app.js& ...

Node.js and MongoDB integration for implementing like and dislike buttons

I have been struggling to create a system for liking and disliking posts in my project. The issue I am facing is with the communication between the server and client side. Here is the form I am using: https://i.sstatic.net/IBRAL.png When I click on the li ...

Watching for changes to an element's visibility within the viewport and automatically scrolling it

I'm having trouble making the input scroll to .here when its value matches "1". Even though I tried using a button with a handle-click function and it worked. Please lend me a hand with this issue. <template> <button @click="scrollToV ...

Utilizing React Router DOM 6.3.0 to read the pathname from an undefined source

I am currently using react-router-dom version 6.3.0 and have set up the following routes inside my App component <BrowserRouter> <Routes> <Route path='/article/*' element={<Article />} /> </Routes> </Brows ...

Utilizing Pushwoosh to Send Push Notifications via VB.net and JSON

I'm currently trying to send a message to a device using the Pushwoosh API through my VB.Net application with a premium account. The code seems to be working fine, but I keep receiving a 400 error code from the server. Any suggestions on what might be ...

Guide on importing npm packages without TypeScript definitions while still enabling IDE to provide intelligent code completion features

I am currently utilizing an npm package that lacks type definitions for TypeScript. Specifically, I'm working with the react-google-maps library. Following their recommended approach, I have imported the following components from the package: import ...

Troubleshooting problem with res.render() in Node.js and Express framework following file saving operation

I'm currently working on a method that involves using async/await and promises to write JSON data to a file before rendering a pug template. However, I've encountered an issue where the code responsible for writing the JSON seems to conflict with ...

What is the best way to incorporate several functions within a resize function?

Is it possible to incorporate multiple functions within the windows.width resize function? I have been experimenting with some code, but I would like to restrict its usage to tablet and mobile devices only, excluding laptops and PCs. Any suggestions on h ...