Separate a JSON object based on its parameters

I'm working with a JSON Object in Typescript and I'm trying to split it into parts. Currently, I am only able to access the keys:

Here is my JSON object:

let data = {
  "dataTest": "data1,data2,data3",
  "insTest": "ins1,ins2,ins3",
  "sertest": "ser1,ser2,ser3"
}

This is how I am looping through it:

for (let key of Object.keys(data)) {
  console.log(key)
}

The current output is:

1º //dataTest
2º //insTest
3º //serTest

What I actually want to see is:

1º //dataTest: "data1,data2,data3"
2º //insTest: "ins1, ins2, ins3"
3º //serTest: "ser1, ser2, ser3"

Elevation

Is there any way to combine all the values into a single array?

For instance:

data1, data2, data3, ins1, ins2, ins3, ser1, ser2, ser3

Answer №1

Utilize the Object.entries() method for extracting key-value pairs from an object.

When used, Object.entries() will generate an array containing the object's enumerable property [key, value] pairs.

To learn more about this method, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

const data = {
  dataTest: "data1,data2,data3",
  insTest: "ins1,ins2,ins3",
  serTest: "ser1,ser2,ser3"
};

const entries = Object.entries(data);

entries.forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

Answer №2

To access the necessary data, you can utilize the method Object.entries().

let info = {
  "infoTest": "info1,info2,info3",
  "detailTest": "detail1,detail2,detail3",
  "recordTest": "record1,record2,record3"
}

Object.entries(info).forEach(([key, values]) => {
  console.log(`${key}: ${values}`);
});

Answer №3

There's an alternative approach

for(const item in info) {
    console.log(item + ': ' + '"' + info[item] + '"');
}

employing Template literals

for(const item in info) {
    console.log(`${item}: "${info[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

Opting for PHP over JSON for the instant search script output

Is there a way to modify my Google Instant style search script, written in jQuery, to retrieve results from a PHP script and output PHP-generated HTML instead of JSON? Below is the current code: $(document).ready(function(){ $("#search").keyup(functi ...

Utilize AngularJs and JavaScript to upload information to a JSON file

Exploring the realm of Angular JS, I am on a quest to create a CRUD form using AngularJs and Json with pure javascript without involving any other server side language. The script seems to be functioning well but is facing an obstacle when it comes to writ ...

What methods can I utilize from Google Maps within Vuex's createStore()?

Currently, I am in the process of configuring my Vuex store to hold an array of Marker objects from the Google Maps Javascript API. Here is a snippet of how my createStore function appears: import { createStore } from "vuex"; export default ...

Sending a POST request from Angular2 to a REST API with Cross-Origin Resource Sharing (CORS

Just diving into the world of Angular 2 and CORS Trying to send form data from Angular 2 to a Rest controller, but encountering an error: Response with Status:0 and Url: Null component.ts --------------------------------------- onSubmit(form:NgForm) { ...

Analyzing an Array and employing a Recursive function to identify Palindromes

I have been assigned the task of building an array by extracting data from a text file that I created myself. The objective of the program is to read the words inputted and store them in an array. Additionally, I am required to design a recursive functio ...

Parsing JSON using Gson with the same key but different values

This is an example of a JSON event: { "type":"record", "name":"Doc", "doc":"adoc", "fields":[ { "name":"id", "type":"string" }, { "name":"user_friends_count", "type":[ "int", "null" ...

bringing in the DefinitelyTyped library for Angular

I am encountering a similar issue as described in this post => Finding the correct import for a third party DefinitelyTyped module In my Angular (TS) project, I am attempting to integrate VanillaTilt. I have used this index.d.ts and saved it in the sam ...

Extract data from a multidimensional unserialized array, count the extracted data, and then sort it alphabetically

Here is a complex array I am working with: Array ( [0] => a:7:{s:21:"mage_form_post_status";s:5:"draft";s:19:"mage_form_post_type";s:4:"post";s:25:"mage_form_post_permission";s:6:"public";s:21:"mage_form_post_author";s:1:"1";s:23:"mage_form_post_redir ...

Flustered by a hiccup in the system, the flutter jsonDecode() function encounters an

While attempting to retrieve data from firestore, I encountered an error while trying to decode it. [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: FormatException: Unexpected character (at character 2) E/flutter (32531): {version: 0, ori ...

Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand. In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5 ...

Incorporating one array into another array with key-value pairs using CodeIgniter

How can I add an array into another array with key value pairs in the CodeIgniter framework? Currently, I have an array structured as follows: Array ( [0] => Array ( [memberName] => Ram [address] => Abc [phoneNo] = ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

Hello, I'm in need of assistance with solving an error issue that I keep encountering. I have been experiencing this problem consistently and am unable to start the remote webdriver

Error: Unable to determine type from provided data. Last 1 characters read: EBuild information - version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'System details: host: 'EX-CON-2255C', ip: &apos ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Learn how to configure gulp-typescript to automatically generate individual JavaScript files for each TypeScript file within the same directory

My interest lies in utilizing the gulp-typescript module for handling typescript compilation. My goal is to set up a configuration where each typescript file translates into one javascript file in the corresponding directory, similar to how it works with t ...

Android Development: Understanding JSON Parsing with Flickr

Looking to extract JSON data from the following URL () but encountering issues with invalid JSON format being returned by the document. Below is a snippet of the response: jsonFlickrFeed({ "title": "Uploads from everyone", "link": " ...

Navigating between different views and pages within Angular FullCalendar can be achieved by utilizing the appropriate handlers for next,

After successfully integrating Angular fullCalendar into my Angular project and displaying events that I can click on, I found myself stuck when trying to handle clicks on the next and prev buttons as well as view changes. Unfortunately, the official docum ...

Creating JSON configuration files for Prometheus targets with SaltStack

How can I include new targets in a json file using Salt? I am utilizing the file_sd_configs file in my prometheus.yml configuration. Here is an example: - job_name: 'winserver_node' file_sd_configs: - files: - targets.json Here is th ...

Determine the total value of prices in the array that fall within a specific range

I have been given the task of creating a method that will take a list of prices, sum them up, and only include those that fall within a specific price range (inclusive), determined by minPrice and maxPrice. The method should then return the total amount. ...

What is the best way to implement useAsync (from the react-async-hook library) using TypeScript?

Currently, I am utilizing react-async-hook to retrieve API data within a React component. const popularProducts = useAsync(fetchPopularProducts, []); The fetchPopularProducts() function is an asynchronous method used to make API calls using fetch: export ...