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

Steps to import a JSON file into a PostgreSQL database

Looking to import a JSON file into PostgreSQL with the following sample data: { "asin":"2094869245", "title":"5 LED Bicycle Rear Tail Red Bike Torch Laser Beam Lamp Light", "price":8.26, "imhUrl":"http://ecx.images-amazon.com/images/I/51RtwnJwtBL ...

Operations such as OR and AND can be used within a JSONB array to filter

Imagine having a table named temp (jsondata jsonb) In Postgres, there is a method to query a jsonb array object for containment check using SELECT jsondata FROM temp WHERE (jsondata->'properties'->'home') ? 'football&apo ...

Accessing the personal data fields of a MongoDB object

My current environment setup includes: NodeJS: 5.7.1 Mongo DB: 3.2.3 MongoDB (NodeJS Driver): 2.1.18 TypeScript: 1.8 I have defined an Object using Typescript as: class User { private _name:string; private _email:string; public get name():strin ...

Get the refreshed values of JSON data

Recently, I've started using Java to fetch data from the web and found myself facing an issue. I am parsing JSON data from a specific website (Flightradar24.com) and saving it into a CSV file. However, as the values in the JSON are regularly updated, ...

Incorporating redux-offline seamlessly into your Angular 5 project

I'm currently grappling with the decision of how to develop an Angular web application that can function seamlessly under offline conditions. While researching possible solutions, I came across react-offline which seems to be a reliable choice for ha ...

Issues arising from an aging Angular project

I'm currently facing an issue with installing node and typescript for an older angular project that I have inherited. This project is using angular 2.4.10 After downloading and installing node version 6.9.5 from the executable file, I proceeded to in ...

Exploring ViewChild Usage in Angular 8's Inheritance

I've encountered an issue with inheritance and ViewChild in a class where I always seem to get undefined. Let me simplify the problem for better understanding. First, let's look at the parent class: @Component({ selector: 'parent', ...

How to send data to an external API using Dart methods and parameters

I would like to send data to my web service using Flutter Dart JSON within my API link. How can I achieve this? ...

Encountered this issue: nw_protocol_get_quic_image_block_invoke dlopen libquic failed

I encountered an issue while attempting to link my API data and display it in the cell. Despite my efforts, I continuously receive a response of == nil. The following code snippets outline the Country.SWIFT // Model.SWIFT // Response.SWIFT components that ...

Using TypeScript for Routing in Angular

I encountered an error message that says the module 'route' is not available. I'm not sure why this is happening, any thoughts? "Uncaught Error: [$injector:nomod] Module 'route' is not available! You either misspelled the module n ...

loading dynamic content into an appended div in HTML using Angular

Here is the HTML code from my app.component.html file: <button mat-raised-button color="primary" mat-button class="nextButton" (click)="calculatePremium()"> Calculate </button> <div id="calcul ...

Blending TypeScript declaration files and Node.js require across various files within an internal module

Is it problematic to mix Node.js modules (require) with TypeScript definition files (d.ts) multiple times within a module? In my case, I organize my modules into namespaces per folder similar to how it's done in C#. After compiling them all using tsc ...

Pause and anticipate the occurrence of AdMob's complimentary video reward event within a defined function in Ionic/Typescript

In my ionic app, I have a function that determines if the user has watched a reward video to access another function: let canUseThisFunction = await this.someService.canUseFunction(); if(canUseThisFunction){ console.log("can use"); } else { cons ...

The specified path is not found within the JsonFilter

Something seems off. I'm using Prisma with a MongoDB connection and attempting to search the JSON tree for specific values that match the [key, value] from the loop. However, I haven't made much progress due to an error with the path property. Be ...

Converting a JSON_ARRAY of IDs to a JSON_ARRAY of values in MySQL 8

I am dealing with a JSON_ARRAY containing ids in the format [1,3,...]. Each id corresponds to a value in another table. Table: animals id | value 1 | lion 2 | monkey 3 | snake Table: animal_owner id | animals_array 1 | [1, 3] 2 | [2] 3 | [] My goal ...

Having trouble retrieving object properties within an Angular HTML template

There are two objects in my code that manage errors for a form: formErrors = { 'firstname': '', 'lastname': '', 'telnum': '', 'email': '' } ValidationMessa ...

Troubles encountered while trying to make MediaRecorder function in Angular 9

Recently, I've been working on integrating Media Recorder into my Angular 9 application by following the instructions provided at this link. However, I have encountered some issues along the way. When I access the page with the Media Recorder compone ...

Parsing JSON data does not involve iterating through an array

Currently, I am receiving data from a Kafka topic using the Telegraf kafka_consumer plugin. The JSON structure that I am working with is as follows: { type: "FeatureCollection", metadata: { generated: Long Integer, url: String, t ...

Utilize JSON parsing with AngularJS

My current code processes json-formatted text within the javascript code, but I would like to read it from a json file instead. How can I modify my code to achieve this? Specifically, how can I assign the parsed data to the variable $scope.Items? app.co ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...