Transform the object into an array and iterate through all its values

How can I transform an object into an array and iterate through each item?

Here is the object I have:

let obj = {
    each_hour: "20000",
    edit_photo: { yes: "20000", no: "0" },
    photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } },
    photograph_gender: { male: "0", female: "20000" }
}

Desired output:

each_hour
20000
edit_photo
yes
20000
no
0
photo_type
Personal
1000
sport
2100
Industrial
1200
...

Answer №1

To manipulate the data stored in the object, you can experiment with utilizing JSON.stringify(), replace(), and split() in the following manner:

let myObj = {
    hours_per_day: "8",
    tasks: { work: "5", break: "3" },
    project_types: { Personal: "100", school: "200", Professional: "300" },
    employees: { total: "10", male: "3", female: "7" }
}
 var result = JSON.stringify(myObj).replace(/["{}]/g,'').split(/[:,]/);
 console.log(result);

Answer №2

To efficiently iterate through your object, a recursive function can be used. If the function receives an array, it can recursively call itself on each element in the array using mapping. When handling objects, you can utilize Object.entries() to get the key-value pairs and perform the same array mapping technique. For non-array or non-object inputs, simply return the value:

function traverseObject(val) {
  if(Array.isArray(val)) {
    return val.flatMap(elem => traverseObject(elem));
  } else if(Object(val) === val) {
    return traverseObject(Object.entries(val));
  }
  return val;
}

const obj = { each_hour: "20000", edit_photo: { yes: "20000", no: "0" }, photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } }, photograph_gender: { male: "0", female: "20000" } }
traverseObject(obj).forEach(e => console.log(e));

An alternative approach involves utilizing the replacer function of JSON.stringify which will be invoked for every key/value pair in the object. However, this method may be considered a workaround:

function traverseObject(obj) {
  const res = [];
  JSON.stringify(obj, (key, val) => (key !== "" && res.push(key, ...(Object(val) === val ? [] : [val])), val));
  return res;
}
// works with arrays -
const obj = { foo: [4, 5, 6], each_hour: "20000", edit_photo: { yes: "20000", no: "0" }, photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } }, photograph_gender: { male: "0", female: "20000" } }
traverseObject(obj).forEach(e => console.log(e));

Answer №3

Here's another way to handle the code with an old-school imperative style and recursion:

In this approach, we maintain an array called `output` where we store key-value pairs obtained from `Object.entries`. If the value is an object, we recursively call the function again, otherwise we add it directly to the `output` array.

Please note that this method is tailored to your specific use case and may not be suitable for general purposes.

let obj = {
    each_hour: "20000",
    edit_photo: { yes: "20000", no: "0" },
    photo_type: { Personal: "1000", sport: "2100", Industrial: "1200", Commercial: "2300", Fashion: "1300", mode: { "name": "farhad" } },
    photograph_gender: { male: "0", female: "20000" }
}


function objToArray(obj){

  const output = [];

  function processing(obj){
  for (const [key,value] of Object.entries(obj)){
    if(typeof value === 'object' ){
       output.push(key);
       processing(value);
    }
    else{
    output.push(key,value);
    }
  }
  }
  
  processing(obj);
  return output;
}

const result = objToArray(obj);
console.log(result);

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

Arrange divs adjacent to each other without any gaps in between

My HTML code includes elements from Twitter Bootstrap and AngularJS framework. <div class="item item-custom-first"> <select class="form-control" style="display:inline; float:right" ng-model="requestdata.units ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

Exploring jQuery: Moving between different table cells using traversal techniques

Seeking assistance from experienced jQuery users as I am new to this library and may not be approaching this task correctly. I have a dynamically generated HTML table that is quite extensive. To enhance user experience, I aim to assign navigation function ...

V-chip fails to trigger parent input event

Struggling to resolve this issue independently, I find myself completely stuck. Any assistance is appreciated. Essentially, this component generates a 100x10 matrix like the one shown below: Threat1: AssetType1 AssetType2 AssetType3 AssetType4 [...] Thre ...

Having issues with AJAX and .change() function not functioning correctly?

I am working on two drop-down menus. The first menu displays the provinces in the country, and when a province is selected, the second menu should show the districts within that province. The following code is for displaying the provinces: $(document).re ...

Adding labels to a JavaScript chart can be done by using the appropriate methods

https://i.stack.imgur.com/uEgZg.png https://i.stack.imgur.com/y6Jg2.png Hey there! I recently created a chart using the Victory.js framework (check out image 1) and now I'm looking to incorporate labels similar to the ones shown in the second image ab ...

Getting rid of the white corners on points using ThreeJS

MY CURRENT PROJECT My current project involves rendering circular points with varying vertex colors using a fragment shader. I am aiming for the points to behave like more performance-efficient spheres, especially when zoomed in for anti-aliasing. ISSUE ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

How can I make my webpage unselectable except for specific content within a div using CSS and JavaScript?

During a live editing session, I am looking to make only specific portions of the page selectable. Can someone provide guidance on how to disable selection for everything except within a particular div? ...

What could be causing my component not to render when using useEffect?

While working on my project, I encountered an issue with the useEffect hook that affected the rendering of my component. The initial code snippet caused the component to fail in rendering correctly: useEffect(() => { setFavoriteContact((item) => ...

Endless time continuum within the scheduling application

Looking for a way to make the time axis in my scheduling app infinite? Currently, it has a fixed length, but I want users to be able to scroll endlessly into the past or future. Any suggestions on how to achieve this? Check out this JSBin for a basic exam ...

Modifying dynamic input fields based on the selected input field type

Seeking advice on a challenge I'm facing while testing a website. My task is to mask input fields in screenshots after executing tests because we share data with other teams. I've tried using JS before the script by changing the input type to &ap ...

Populating a MySQL database with data from an array using PHP

Struggling a bit with this task and hoping for some guidance. The challenge is to transfer shopping cart basket products from MySQL to an "order-details" table at checkout, rather than using sessions in this case. The product array is successfully create ...

creating a fresh window using AJAX in Ext JS

While I know there may be similar questions out there, the details of my situation are unique. I'm facing an issue with building a new window using ExtJS, starting from a pre-existing grid. The goal is to populate this new window with references to el ...

Troubleshooting Python: Dealing with Bugs in Binary Search Tree Objects

I encountered a minor bug in my program that I couldn't rectify on my own. I would greatly appreciate it if someone could assist me in pinpointing the issue. The crux of the problem lies in two functions. The first one converts a sorted array into a b ...

Adjust the parent div's background color when a radio button is selected

Is it possible to dynamically change the background color of a div that contains a radio button when the button is checked? Here is an example of the HTML code: <div class="custom-container"> <input id=“example” type="radio" name="opt ...

Utilizing AngularJS for toggling data with ng-click

In my project, I have a unique issue with a list item that toggles a modal and sets a parameter using ng-click. Strangely, when calling a specific function in another location, Course.SelectedCourse returns as undefined, even though Course.ID has a valid ...

Issue with integrating petfinder API with a ReactJS application

I'm encountering an issue with the interaction between the petfinder API and ReactJS. The functionality works smoothly until I attempt to access the "pets" object/array. import React, { Component } from 'react'; import { getPets } from &apos ...

Which is better for creating forms: ASP.NET or Angular.JS?

Good day, I am currently working on creating an internal form for the staff of a blog to submit specific information that will be posted later. The form is being developed in ASP.NET with some Javascript Controls. The issue I am facing is that my server ...

Continuously looping in Firefox on Android is the setInterval function

I have a brief section of JavaScript that I would like to use to check a server every few seconds and update the DOM. function updateCard() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState ...