Updating the Structure of Various Objects with an Object Model Schema

Hello there,

Query: Can you provide guidance on constructing a function that does the following:

  1. Accepts an object as the first argument;
  2. Takes a schema model as the second argument;
  3. The second argument is an array of objects with different models than the first argument;

Objective: The desired outcome is to return an array of objects with the following modifications:

  1. All properties that do not exist in the first argument (object model) should be removed from each element;
  2. Non-existent properties in each element should be created with a NULL value;
  3. Existing properties in each element should remain unchanged;

Example - Function call:

    standardizeWith({id: 1, name:'abcd'}, [{name:'Carlos', age:30}, {a:'x', b:'y', c:'z'}])

  // **output:**
  // 0:{name: "Carlos", id: null}
  // 1:{name: null, id: null}

const standardizeWith = (object,array) => array.reduce(
    (accumulator, { id, name}, index) => (
      {
        ...accumulator,
        [index]: {id, name}
      }),
    {} 
   );
   
   
   console.log(standardizeWith({id: 1, name:'abcd'}, [{name:'felipe', age:27}, {a:'x', b:'y', c:'z'}]));

However, this solution may be too specific for a more generic problem. Any suggestions?

Answer №1

There is a simple solution using the map() and reduce() functions. It would be more convenient if you could modify it to return undefined instead of null for non-existing keys:

function standardizeWith(schema, obj) {
  return obj.map(item => Object.keys(schema)
            .reduce((a, key) => (a[key] = (item[key] !== undefined ? item[key] : null), a), {}))

}

let result = standardizeWith({id: 1, nome:'abcd'}, [{nome:'Carlos', idade:30}, {a:'x', b:'y', c:'z'}])
console.log(result)

Answer №2

In my opinion, the .map function is more suitable for this task since it allows you to map one array to another.

function standardizeWith(schema, array) {
  let keys = Object.keys(schema);
  return array.map(obj => {
    let newObj = {};
    // creating a new object using keys from schema
    keys.forEach(key => {
      // using existing object's key if it exists; otherwise assigning null
      newObj[key] = obj.hasOwnProperty(key) ? obj[key] : null;
    });
    return newObj;
  });
}

console.log(
  standardizeWith({id: 1, name:'abcd'}, [{name:'Carlos', age:30 }, {a:'x', b:'y', c:'z'}])
)

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

The Vue 2.0 instance seems to be failing to listen to events emitted by vue-router components

Currently, I am working with Vue 2.0-rc.6 and Vue-router 2.0-rc.5, the latest versions available. I attempted to use this.$emit('custom-event') in one of my router components and this.$on('custom-event', () => { console.log('I ...

easy method to sort elements in a multi-dimensional array using php

I have a multi-dimensional array called $locations and I need to filter out the location that matches both the country_name and city_name. If multiple arrays match, I only want one array returned. $country = 'United States'; $city = 'Miami& ...

Error: monaco has not been declared

My goal is to integrate the Microsoft Monaco editor with Angular 2. The approach I am taking involves checking for the presence of monaco before initializing it and creating an editor using monaco.editor.create(). However, despite loading the editor.main.j ...

What's the process for creating a synchronous function in AngularJS?

Is there a way to make storyboard.getAdressTimeLine run synchronously? I need storyboard.drawTimeLine to continue executing only after storyboard.getAdressTimeLine is done for (var i = 0; i < response.data.length; i++) { var obj=response.data[i]; var d ...

What is the process of transforming a tree into a JSON object?

I have a tree structure that I need to convert into JSON format for use with a jquery option tree. NodeId, Title, Level 1, cars, 0 2, boats, 0 3, oldtimer, 1 4, trucks, 1 5, heavytrucks, 4 The desired tree structure is as follows: boats cars - oldtimer - ...

Using AngularJS UI Bootstrap tooltips in conjunction with Bootstrap 4: A complete guide

When using the directive <div uib-tooltip="hello-world" tooltip-is-open="true">hello world</div>, an error occurs: Failed to load template: uib/template/tooltip/tooltip-popup.html This website is utilizing both ui-bootstrap.js and ui-bootstra ...

The API GET request is not returning any data, even though Postman is able to retrieve the

While attempting to make an API call to a remote server, I encountered the following error initially: No 'Access-Control-Allow-Origin' header is present on the requested resource. To temporarily resolve this issue, I appended the https://cors- ...

Instructions for creating a nested list using a delimited string or an array:

Here are the results from my SQL query: Maths Maths|Algebre Maths|Algebre|Algebre 1 Maths|Algebre|Algebre 2 Maths|Algebre|Algebre 3 Maths|Analyse Maths|Analyse|Analyse 1 Maths|Analyse|Analyse 2 Maths|Probabilité physics I have tried various methods to c ...

Modify HTML tags based on the sum of <li> elements using jQuery

I have a dynamic slider with items in a list that will change based on the page. My goal is to create a loop that updates the data-slide-to attribute with the correct slide number for each item. After several attempts, I managed to come up with a solutio ...

How to successfully send data props from child components to parent in Vue3

I am currently working on a personal project to add to my portfolio. The project involves creating a registration site where users can input their personal data, shipping information, and then review everything before submission. To streamline the process ...

JavaScript function is not being invoked when receiving PHP arguments

When using the < a > tag in php, I encountered an issue where passing an argument in a JavaScript function did not result in the function being called. However, if I passed empty arguments, the function was executed. Here is the JavaScript code: fu ...

Utilize a checkbox located within a table to obtain or delete the ID with the help of

Greetings everyone, I am currently working on creating a table with checkboxes. The goal is to add the ID to an array of objects when the checkbox is clicked and remove it when unchecked. Here is a snippet of my code: HTML Table ... <td><input ...

Is it possible to use JavaScript to extract data associated with a specific h2 class on a webpage and then present that information?

Just curious if it's feasible, not looking for actual code. For instance, say I have an h2 class called "stock-number" with a value of #NC123456. Is it possible for JavaScript to access each instance of that class, retrieve data from a different datab ...

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

React Menu Toggle

Currently, I am trying to create a Toggle right menu using React following this example: how-to-build-a-sliding-menu-using-react-js" The issue arises because React.createClass is deprecated, forcing me to modify the code which has resulted in it no longer ...

A guide on updating object values within an array using map in React

Is there a method to calculate the total sum of specific values from an array of objects? Example array: const exampleArray = [ {item_id: 1, quantity: "3"}, {item_id: 2, quantity: "5"}, {item_id: 3, quantity: "2"} ] In this case, I want to add up the qua ...

Chrome Extension for Extracting Data from Websites

I am in the process of developing my Google Chrome extension that needs to store a variable from another website by passing it over. Below is the snippet of code found in the script.js file of the website: var editorExtensionId = "extension"; & ...

Code running successfully in Chrome's console, but encountering issues when executed on the webpage

Having some trouble assigning a function to a button in JavaScript. This is the button I'm working with, and my main goal right now is to make it responsive. <button id="artbtn" class="artbtn btn">Art</button> I experimented with this in ...

Unset the class upon clicking outside the div, but maintain the class unset when the div is closed

I have a div that opens when the question mark icon in the upper right corner of the document is clicked. When clicked, a class is added which transforms the question mark into a close icon. When clicking outside the div, the div closes and the class is re ...

Discovering the specific marker that was clicked from a group of Google map markers

I have a collection of marker objects named markers. I am currently utilizing a for loop to assign event listeners to each one. However, I am encountering difficulty in determining which specific marker was clicked. This is the current code snippet I have ...