Are you searching for ways to convert an object into an array?

I have a dynamically built object and I need to extract specific fields (the dynamic ones) from it and convert them into an array.

In the following code snippet, my goal is to convert towers[X] into an array of objects.

{id: "", description: "Teste", towers[1]: true, towers[2]: true, 
    towers[3]: true, …}
    description: "Test"
    id: ""
    towers[1]: true
    towers[2]: true
    towers[3]: true
    towers[4]: ""
}

The desired outcome would look something like this:

{
    id: "",
    description: "Test",
    towers[1]: true //Can remain here or be omitted as it won't be used
    ...
}

This should result in a new array structured like:

{
    [id: 1, value: true],
    [id: 2, value: true],
    [id: 3, value: true],
    [id: 4, value: ""]
}

Answer №1

Assuming that towers[0] returns a number, you can try this method. It identifies all keys in an object with boolean values and retains them by adding them to a new object.

const obj = YOUR_OBJECT_HERE;
Object.keys(obj).filter((key) => typeof obj[key] === "boolean").reduce((accum, key) => {
    return {...accum, [key]: obj[key]};
}, {})

Answer №2

When X is a numeric value and obj represents the object we aim to convert:

let output = [];
for (let index = 1; index <=x ; i++) {
output.push({number:index, tower: obj['towers'+index]})
}

Answer №3

If you are looking to change your array of objects, one way to do it is:

this.objects = this.objects.map(object => {
    return {
        id: object.id,
        description: object.description,
        towers: Object.keys(object).filter(key => key.indexOf('towers') != -1)
            .map((key, index) => {
                return {id: index + 1, value: object[key]}
            })
            .filter(x => x.value)
    }
})

Take note that the "map" function includes an "index" starting from 0.

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

Using Long Polling with Angular 4

I am looking for a way to monitor the progress of a certain task using API calls. To achieve this, I have developed a service that executes these API calls every 1.5 seconds Main Component private getProgress() { this.progressService.getExportPr ...

Various types of generics within an object

Is there a way to achieve different types for the nested K type within a type like MyType? Here's an example: type Config<K> = { value: K; onUpdate: (value: K) => void; } type MyType<F extends string> = { [K in F]: <V>() =& ...

A destructured object with a Typescript interface

While working on a React / TypeScript project, I encountered an error involving destructuring an object. The issue arises when I try to destructure notificationData within the publish function. An error message stating "Property 'messages' does ...

Explanation on How to utilize the $( document ).ready() jQuery function within the ngAfterViewInit() on a Component class using Angular 2

This is the code snippet: constructor(private el: ElementRef) { } ngAfterViewInit() { this.loadScript('app/homepage/template-scripts.js'); } ...

Tips for resolving this unhandled error in React TypeScript

After creating a program in React TypeScript, I encountered an uncaught error. Despite running and debugging tests and conducting extensive research on Google, I have been unable to resolve this issue on my own. Therefore, I am reaching out for assistance ...

Trouble parsing JSON in Classic ASP

After receiving a JSON Response from a remote server, everything looks good. I discovered an helpful script for parsing the JSON data and extracting the necessary values. When attempting to pass the variable into JSON.parse(), I encountered an error which ...

Angular 2: Issue with data table not updating after item deletion

I need assistance with updating a data table after deleting an item. The database is updated correctly when I delete an item, but the table does not automatically refresh to reflect the changes. managenews.component.ts import { Component, OnInit } from ...

Best practice for incorporating types into a Redux-toolkit reducer

As someone who is relatively new to TypeScript, I have a specific goal in mind. I am looking to create an interface where: interface ActionType { fieldName: {any one key from the interface FormStateType listed below such as 'name', 'age&ap ...

Performing Bag operations concurrently with Python Dask

I'm currently working on processing a JSON file using Dask and read_text. However, I've noticed that only one core is being utilized at 100% when I check the Linux Systems Monitor. How can I determine if my operations on a Dask Bag can actually b ...

If the key is not found in the JSON data, assign a value of null and add it to the

My goal is to extract a value from a specific key in a JSON string and then insert that data into a dataframe. However, the column may or may not appear in the structure. When the key does not exist, it throws an error like 'KeyError': 'Co ...

Error encountered during package installation: npm command terminated with exit code 1

When working with Angular 2, I consistently encounter the same issue across all of my projects. Strangely, these issues are normally resolved when building on a different PC. view image description here ...

Tips for properly formatting a string in JSON format to ensure it is correctly identified as a JSON file

I have a string and I'm looking to format it in JSON. When trying to do so, I receive a warning message in Visual Studio stating that the string is not formatted properly as JSON. I am exploring if there is a way to achieve this. { "speaker": 0, " ...

href variable for server-side data table

Currently, I am implementing the server-side datatables plugin using an example from http://datatables.net/examples/data_sources/server_side.html While the example works well, I find myself needing to modify the code for my table to better suit my desired ...

Experiencing difficulty in transferring array information from a parent component to a child component within an

I'm currently working on a task where I need to pass data from a parent component to a child component. The data consists of an array that is nested within another array. parent.component.html <div *ngFor="let parent of parentArray; index as ...

Set the class function to be uninitialized

I'm a little unsure of my TypeScript knowledge. I have a class MyClass with a member variable that is a function, but I don't know what this function will be at compile time. I want to allow external code to set this function dynamically during r ...

Modifying the values of various data types within a function

Is there a more refined approach to enhancing updateWidget() in order to address the warning in the else scenario? type Widget = { name: string; quantity: number; properties: Record<string,any> } const widget: Widget = { name: " ...

Unable to confirm the version of Angular

I am currently using node version 10.14.1 and npm version 6.4.1 with angular version 7.0.3 installed. However, when I try to check the angular version by running the ng --version command, I encounter an error message in the command prompt. C:\Users&b ...

What is the best way to identify modifications in a JSON object?

import QtQuick 2.12 import QtQuick.Window 2.12 import QtQuick.Controls 2.0 Window { visible: true width: 640 height: 480 property var json: { "name": "old" } Component.onCompleted: json.name = "new" onJsonChanged: co ...

How to generate a fresh JSON file by extracting unique elements from a JSON array using PHP

I have a JSON object that resembles the following: OBJECT $deals [ { "deal_id": 124563 "merchant_id": 123 "merchant_name": Merchant1 } { "deal_id": 456789 "merchant_id": 123 "merchant_name": Merchant1 } { "deal_id": ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...