Building on Angular 7, generate a fresh object by extracting specific values from an existing object

My object structure is as follows:

const Obj =
"Value1": {
    "value1value": "1"
},
"Value2": {
    "value2value": "2"
},
"Value3": {
    "value3value": "3"
},
"BTest": {
    "1": "1",
    "2": "2"
},
"Value4": {
    "value4value": "value4value"
},
"ATest": {
    "1": "1",
    "2": "2"
},
"Value5": {
    "value5value": "value5value",
    "value6value": "value6value"
},
"TestA": {
    "1": "1",
    "2": "2"
};

I am looking to create a new object with the following structure:

cont newObject = 
    "Value1": {
        "value1value": "1"
    },
    "Value2": {
        "value2value": "2"
    },
    "Value3": {
        "value3value": "3"
    },
    "Value4": {
        "value4value": "value4value"
    },
    "Value5": {
        "value5value": "value5value",
        "value6value": "value6value"
    };

I have attempted to filter out some values using this code snippet:

const newObject = Obj.map(o => {
          return {  };
        });

Unfortunately, my attempts were unsuccessful. Any suggestions on how to achieve this? Thank you in advance.

Answer №1

Seems like you are interested in extracting keys that begin with a specific value. You can achieve this by using the following code snippet:

var obj={"Value1": {
    "value1value": "1"
},
"Value2": {
    "value2value": "2"
},
"Value3": {
    "value3value": "3"
},
"BTest": {
    "1": "1",
    "2": "2"
},
"Value4": {
    "value4value": "value4value"
},
"ATest": {
    "1": "1",
    "2": "2"
},
"Value5": {
    "value5value": "value5value",
    "value6value": "value6value"
},
"TestA": {
    "1": "1",
    "2": "2"
}}

let newObj={};

Object.keys(obj).forEach(k=>{
if(k.startsWith('Value')){
newObj[k]=obj[k];
}
})
console.log(newObj)

Answer №2

If you prefer not to utilize startwith, and instead opt for using full names, consider creating an array with the names you wish to eliminate. Then, simply check and add keys that are not in that array to a new object. Here's an example of how to do this:

const removableItems = ["TestA", "BTest", "ATest"]
let newObj = {}
for (var key in obj) {
   if (obj.hasOwnProperty(key) && !removableItems.includes(key)) {
      newObj[key] = obj[key];
   }
}

You can view a demo of this concept on StackBlitz.

Answer №3

To merge objects in JavaScript, you can utilize a combination of various methods such as Object.assign() and Spread syntax, along with Object.keys(), Array.prototype.filter(), Array.prototype.map(), and String.prototype.startsWith():

const ObjectA = {"Key1": {"value1key": "1"},"Key2": {"value2key": "2"},"Key3": {"value3key": "3"},"SubTest": {"1": "1","2": "2"},"Key4": {"value4key": "value4value"},"MainTest": {"1": "1","2": "2"},"Key5": {"value5key": "value5value","value6key": "value6value"},"SampleTest": {"1": "1","2": "2"}};
const mergedResult = Object.assign(
  {},
  ...Object.keys(ObjectA)
    .filter(key => key.startsWith('Key'))
    .map(key => ({ [key]: ObjectA[key] }))
);

console.log(mergedResult);

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

rxjs "switch to" once the expansion is complete

I am currently working on the following code snippet: const outputFile = fs.createWriteStream(outputPath); const requisitionData = this.login().pipe( map(response => response.data.token), switchMap(loginToken => this.getRequisitions( ...

Issue with breakpoints functionality in MUI v5 and React project

I've been attempting to utilize breakpoints for responsive design on my website, but unfortunately, it doesn't seem to be working correctly. Every time I implement a breakpoint, the entire page goes blank. Below is the code snippet I am working w ...

Troubleshooting Angular Build Errors: Integrating Three.js

Upon setting up a new Angular application and integrating three along with @types/three, I proceeded to create a basic component. However, upon executing ng build --prod, the following errors are displayed: ERROR in node_modules/three/src/core/BufferAttri ...

Angular - Exploring the Dynamic Validation of Multiple Fields Across Components

Currently in the process of developing a classifieds site using Angular. The main component of the route is structured as follows: Contains static fields (name, email, phone, location, etc.) defined in its template Includes a dynamically loaded compo ...

Python Selenium - Handling StaleElementReferenceException

Currently, my attempt is to scrape multiple webpages from a site named iens. I have successfully scraped one page already. This is the code I have so far: chrome_path = '/Users/username/Downloads/chromedriver' driver = webdriver.Chrome(chrome_p ...

Utilize Django to leverage a JSON file stored within a context variable for use in jQuery

I need to utilize a list in Jquery and integrate it with the Autocomplete jQueryUI widget. The list is small, so creating a new request seems unnecessary. Therefore, I believe using Jsquery's getJSON is also not required. Here is my current setup: ...

Exploring NuxtJS Vuex Module namespaces and mutation enumerations

My NuxtJS website has a Vuex store with a root state and a module located at store/shop/cart/state.ts. Within the module, there is a file called store/shop/cart/mutations.ts. import { MutationTree } from 'vuex'; import { CartState } from './ ...

An issue arises with the Datatables destroy function

Utilizing datatables.js to generate a report table on my page with filters. However, when applying any of the filters, the data returned has varying column counts which prompts me to destroy and recreate the table. Unfortunately, an error message pops up ...

The best approach for setting a select value and managing state in React using TypeScript

Currently, I am in the process of familiarizing myself with TypeScript within my React projects. I have defined a type for the expected data structure (consisting of name and url). type PokedexType = { name: string; url: string; } The API respon ...

Typescript: Add a new variable preceding a specified string

fetchArticle(articleId: string): Observable<any> { return this._http.get(`${this._url}/${articleId}`) .map((response: Response) => response.json()) .do(value => console.log(value)) .catch((error) => Observable.throw(err ...

How to use Angular template syntax to assign an async array to multiple variables

When working in JS, there is a clever method for assigning values from an array to new variables with ease: let [a, b, c] = [1, 2, 3]; // a = 1, b = 2, c = 3 I started thinking about whether I could achieve a similar elegant solution using Angular's ...

Responsive Gallery Grid Slider with uniform height boxes

Looking to develop a responsive gallery grid slider with equal height boxes. For instance, at 650px wide or wider, display 3 columns and 2 rows. When the width is 550px or less, switch to 2 columns and 3 rows. If the width is 450px or less, go down to 1 ...

Encountering NullInjectorError while testing Angular unit tests: DatePipe provider is missing

I have been working on implementing unit tests for a service that has dependencies injected from two other services. One of the injected services utilizes the Angular DatePipe, so I am utilizing the Angular TestBed to automate the process. However, when ru ...

Building a stylish bootstrap button within the cell rows of a table using jquery

I need to insert a button in the "Details" column. <button class="btn btn-primary btn-fab btn-icon btn-round"> Here is my code: var tableRef = document.getElementById('ticker_table').getElementsByTagName('tbody')[0]; var ti ...

Transform the dataUrl into a blob and send it via ajax request

I am currently utilizing the imgly image cropper plugin with some modifications for my application. It has the ability to convert an image into a dataUrl and produce the image as a base64 image which can then be saved as a jpeg. My objective is to adjust ...

Leveraging AngularJS $filter in conjunction with ng-disabled

I have a variable in my $scope that contains information about an election, including a list of voters with unique IDs: $scope.election = { voters: [ { _id: '123' }, { _id: '456' }, { _id: '789' } ] } Additio ...

Error Not Captured: [$rootScope:infdig]

Here is a code snippet that I wrote: <tbody ng-repeat="dtataOne in dataOnes()"> <tr> <td>My Data</td> <td class="task-container ui-sortable" colspan="6" ng-model="dtataOne.MyModel" ui-sortable="sortableOption ...

Step-by-step guide on implementing a see-more/read-more feature using only anchors in the HTML

I am currently developing a website that will be managed by individuals who are not very tech-savvy. I want to empower them with the ability to add "see-more" anchors that utilize jQuery slide up/down functionality to reveal content. While my code works w ...

What is the best way to present these values with spaces in between each word?

When I use console.log(JSON.stringify(selected["1"]?.others)), the output is: ["Cars","Books","Necklaces"] On the screen, however, when displaying this data, all the words appear together without spaces. It looks li ...

Add HTML syntax highlighting to a text area for coding purposes

I am facing a seemingly straightforward issue, but I worry that it may be too complex for me to handle on my own. My goal is to incorporate a textarea into a webpage where users can input HTML code, click a button, and have the interpreted HTML displayed i ...