Ways to package object fields within an array

I am in possession of an object with various properties, ranging from arrays to objects.

My goal is to transform the object so that each sub field is encapsulated within an array.

For instance:

"head": {
            "text": "Main title",
            "sub": {
                "value": "next"
            },
            "place": "secondary"
        }

The 'head' field contains an object. I aim to have the object enclosed in an array like this:

"head": [{
            "text": "Main title",
            "sub": {
                "value": "next"
            },
            "place": "secondary"
        }]

I have recognized that maintaining the structure consistent for every item is essential.

I attempted to achieve this using interfaces but encountered issues as the object type varies. As a result, I seek to retain the structure.

If there are better methods to convert the object into a suitable interface, I would appreciate hearing about them.

Thank you!

Answer №1

This function will iterate through each value recursively, converting it to an array if it is not one already, while excluding keys specified in the keysToSkip array.

const obj = {
  "head": {
    "text": "Main title",
    "sub": {
      "value": "next"
    },
    "place": "secondary"
  },
  "alreadyArray": [
    "val", "val2"
  ]
}

const keysToSkip = ["value"]

let depthFirstLoop = (obj) => {
  Object.keys(obj).forEach((key) => {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      depthFirstLoop(obj[key]);
    }
    if (!Array.isArray(obj[key]) && !keysToSkip.includes(key)) {
      obj[key] = [obj[key]]
    }
  });
};

depthFirstLoop(obj)

https://jsfiddle.net/9p7k64ec/26/

Answer №2

It is generally recommended not to modify an object while iterating through it. It is a better practice to create a new object instead.

const originalObj = {
  "header": {
    "text": "Main heading",
    "subheading": {
      "value": "next value"
    },
    "location": "secondary"
  }
}
var copiedObj = {}

for (property in originalObj){
    copiedObj[property] = [originalObj[property]]
}

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

How can I retrieve the number of links pointing to a specific property within a JavaScript object

I am faced with the following dataset: const main = 'test1'; const data = [ { from: 'test1', to: 'test2' }, { from: 'test2', to: 'test3' }, { from: 'test3', to: ...

Tips for iterating through a JSON object's values with jQuery AJAX

Is there a way to iterate through the json data with HTML content fetched from an ajax call in Jquery? For instance, I want to calculate the number of li tags within the provided data that have a specific class. I am looking to count the number of li tags ...

What are some alternative ways to refactor my code in AsyncTask without using runOnUiThread?

Greetings to all Android developers! I am facing an issue with the compatibility of my old code and API 18. All the codes below work perfectly on Android 2.3. However, when I attempt to run them on a newer API version, it results in a crash. Is there a w ...

The module has defined the component locally, however, it has not been made available for

I have developed a collaborative module where I declared and exported the necessary component for use in other modules. import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DateslideCompone ...

Analyzing individuals within an array

Currently, I am faced with a particular challenge. In my dataset, there is an array of individuals where some names are duplicated but not identical due to slight variations. My task involves iterating through all the names to assess their similarity, fol ...

CUDA/C++ implementation for searching in a table of positive integers

Currently, I am working on optimizing a section of code for a CUDA application that involves mapping unsigned integer ranges to array indexes, like [0..~1000]: if n >= 0 and n < 8 then index 0 if n >= 8 and n < 10 then index 1 and so on. Cons ...

Combining cURL responses to create a unified json output: Guide

I want to customize how my file output is displayed. Currently, it shows the JSON files side by side, but I prefer them to be merged together. Here is my code: <?php $curlData = array( array( 'url' => 'https://example.com/list ...

PHP code to filter out repeated numbers in an array and display the unique digits

I feel like I might be overthinking things a bit. I have an array with sets of values like [1,9], [4,6] [5,5], [6,4], [9,1] and some of them have duplicate digits (I'm having a brain freeze and can't even remember the term for numbers like this) ...

Get notified with ng2-smart-table updates when editing

I am trying to control the edit feature of my ng2-smart-table, but the code I have isn't working. Am I missing something? HTML <ng2-smart-table [settings]="settings" [source]="source" (edit)="onEdit($event)"></ng2-smart-table> Component ...

Merging Promises in Typescript

In summary, my question is whether using a union type inside and outside of generics creates a different type. As I develop an API server with Express and TypeScript, I have created a wrapper function to handle the return type formation. This wrapper fun ...

Can you pass a generic type as a parameter for another generic in Java?

Simply provide a generic type like a callback: type FUNC<ARG,RET, F> = (arg: ARG) => F<RET>; type PROMISE<T> = Promise<T>; type IDENT<T> = T; type A = FUNC<number, void, IDENT>; type A_PROMISE = FUNC<number, void, ...

How can I set up Prettier to exclude a line following a specific pattern?

Is there a method to configure Prettier in Visual Studio Code to exclude lines following a specific pattern? Sometimes, I require a directive like /**@ts-ignore */ followed by a lengthy line. However, when Prettier formats the code, it introduces new line ...

There was an issue with parsing the JSON: Unable to convert an Array value to type ""

I am working with an object called Event, which has properties such as Long id, String name, LocalDateTime start, LocalDateTime stop, and Desk desk(Long id, String name). I need to save this object in a database using a Create method: @PostMapping("/flexof ...

Obtain an array containing only unique values from a combination of arrays

Is there a simple way or plugin that can help me combine values from multiple arrays into one new array without duplicates? var x = { "12": [3, 4], "13": [3], "14": [1, 4] }; The resulting array should only contain unique values: [1, 3, 4]; ...

I'm looking to receive the specific data types for express request arguments. How can I

Currently, I am working on incorporating authentication into an express application using passport and typescript. For defining the user model, I have utilized typegoose. Once the login request passes through the passport strategy, a login method is called ...

Using subscribe method to return an observable within a function

Looking to develop a service that interacts with the Spotify API, I require an authorization bearer token. The token is obtained from another service, which returns an observable. How can these two components be integrated together? Initial attempt: getS ...

Establishing a Next.js API endpoint at the root level

I have a webpage located at URL root, which has been developed using React. Now, I am looking to create an API endpoint on the root as well. `http://localhost:3000/` > directs to the React page `http://localhost:3000/foo` > leads to the Next API end ...

Issue with accessing data from database in my app

I am currently working on a project that involves retrieving data from my database. The user inputs a car registration number and a rating (ranging from 1 to 5) and then clicks a button. Upon clicking the button, my code is supposed to execute, fetching te ...

ionChange - only detect changes made in the view and update the model in Ionic 2

In my Ionic 2 application, I have a feature that allows users to schedule notifications as reminders. The requirements for this feature are as follows: Upon entering the reminder page, it should check if there is a saved reminder. If a reminder is saved ...

Remap Objects Function with Correct Return Data Type

After receiving data from another source via a post request in a large object, I need to extract specific fields and organize them into more precise objects with some fields remapped before inserting them into a database. Currently, I have a working solut ...