The Wayback Machine - https://web.archive.org/web/20240927032523/https://www.geeksforgeeks.org/how-to-create-an-array-of-partial-objects-from-another-array-in-javascript/
Open In App

How to create an array of partial objects from another array in JavaScript ?

Last Updated : 02 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Creating an array of partial objects from another array is a useful technique in JavaScript, especially for data transformation and manipulation. This guide covers various methods to efficiently create these arrays, enhancing your ability to work with complex data structures.

Importance of Creating Partial Objects:

Creating partial objects is crucial for:

  • Simplifying data structures for specific use cases.
  • Improving performance by reducing the size of data handled.
  • Enhancing readability and maintainability of code by focusing on relevant properties.

These are some common methods:

1. Using the map() method

By using the map() method we can create an array of partial objects from another object’s array. The map() method takes the keys of the object array as the parameters which are required to be in the desired object array and returns the key-value pairs of that particular key. In the below example, we obtain the key-value pairs of the name and age as the array of partial objects of which the parameters are given in the map method.

Syntax:

partialObjectArray = ObjectArray.map((
{key 1, key 2, ...key n}) => ({key 1, key 2, ...key n}));

Note: key 1, key 2, …key n are the fields that are needed in the partial object array

Example: This is the illustration of creating an array of partial objects from another array using the map() method.

JavaScript
let = studentDetails = [
    {
        name: 'dinesh',
        age: 20,
        marks: 30,
        Grade: 'F'
    },
    {
        name: 'divi',
        age: 20,
        marks: 60,
        Grade: 'B'
    },
    {
        name: 'vignesh',
        age: 30,
        marks: 80,
        Grade: 'A'
    }]
let partialStudentDetails = studentDetails.map((
    { name, age, Grade }) => ({ name, age, Grade }));
console.log(partialStudentDetails);

Output
[
  { name: 'dinesh', age: 20, Grade: 'F' },
  { name: 'divi', age: 20, Grade: 'B' },
  { name: 'vignesh', age: 30, Grade: 'A' }
]

2. Using Destructuring

Rather than giving all the required fields of the object array in the map() method which is a difficult task if there are multiple fields in the object. we can use the map method in the below way to create a partial object array. The first parameters must be the fields that are not needed in the resultant object array. 

Syntax:

partialObjectArray = ObjectArray.map(({ key 1, key 2, ...rest }) => rest);

Note: key 1, and key 2 are the fields that are not required in the resultant object array.

Example: This is another illustration to create an array of partial objects from another array using the map() method.

JavaScript
let = studentDetails = [
    {
        name: 'dinesh',
        age: 20,
        marks: 30,
        Grade: 'F'
    },
    {
        name: 'divi',
        age: 20,
        marks: 60,
        Grade: 'B'
    },
    {
        name: 'vignesh',
        age: 30,
        marks: 80,
        Grade: 'A'
    }]

// The parameter marks is not required 
// in the resultant object array

let partialStudentDetails = studentDetails.map((
    { marks, ...rest }) => rest);
console.log(partialStudentDetails);

Output
[
  { name: 'dinesh', age: 20, Grade: 'F' },
  { name: 'divi', age: 20, Grade: 'B' },
  { name: 'vignesh', age: 30, Grade: 'A' }
]

In the above example, we get name, age, and marks key-value pairs in a partial object array.

3. Using reduce Method()

Reduce method also use to iterate over an array and create a single value and object,

Example: In this example, we are using reduce method to create a partial object from another array.

JavaScript
let studentDetails = [
    {
        name: 'dinesh',
        age: 20,
        marks: 30,
    },
    {
        name: 'divi',
        age: 20,
        marks: 60,
    },
    {
        name: 'vignesh',
        age: 30,
        marks: 80,
    }]

const partialStudentDetails = studentDetails.reduce((res, item) => {
    res.push({ name: item.name, age: item.age, marks: item.marks });
    return res;
}, []);
console.log(partialStudentDetails);

Output
[
  { name: 'dinesh', age: 20, marks: 30 },
  { name: 'divi', age: 20, marks: 60 },
  { name: 'vignesh', age: 30, marks: 80 }
]

4. Using forEach() method

The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array. 

Syntax:

array.forEach(callback(element, index, arr), thisValue);

Example: In this example, the forEach() method is used to iterate over each object in the originalArray. For each object, a new partial object is created with selected properties (in this case, id and name), and it is pushed to the partialObjectsArray.

JavaScript
// Original array of objects
const originalArray = [
  { id: 1, name: 'John', age: 30 },
  { id: 2, name: 'Alice', age: 25 },
  { id: 3, name: 'Bob', age: 35 },
];

// Array to store partial objects
const partialObjectsArray = [];

// Using forEach() to create partial objects
originalArray.forEach(obj => {
  const partialObj = {};
  partialObj.id = obj.id;
  partialObj.name = obj.name;
  // You can include other properties as needed
  partialObjectsArray.push(partialObj);
});

console.log(partialObjectsArray);

Output
[
  { id: 1, name: 'John' },
  { id: 2, name: 'Alice' },
  { id: 3, name: 'Bob' }
]

5. Using a for Loop

To create an array of partial objects using a for loop, iterate over the original array, destructure the desired properties, and push new objects containing these properties into a result array. This method extracts and collects specific fields efficiently.

Example:

JavaScript
let studentDetails = [
    {
        name: 'dinesh',
        age: 20,
        marks: 30,
    },
    {
        name: 'divi',
        age: 20,
        marks: 60,
    },
    {
        name: 'vignesh',
        age: 30,
        marks: 80,
    }
];

const partialStudentDetails = [];
for (const student of studentDetails) {
    partialStudentDetails.push({
        name: student.name,
        age: student.age,
        marks: student.marks
    });
}

console.log(partialStudentDetails);

Output
[
  { name: 'dinesh', age: 20, marks: 30 },
  { name: 'divi', age: 20, marks: 60 },
  { name: 'vignesh', age: 30, marks: 80 }
]

Using Array.from() with map()

Using Array.from() with map allows creating a new array by mapping each element from an iterable (like an array or array-like object). It converts the iterable to an array and applies a mapping function to each element, returning a new array based on the mapped results.

Example: In this example we creates a new array partialObjects containing objects with id and name properties extracted from originalArray using Array.prototype.map.

JavaScript
const originalArray = [
    { id: 1, name: 'Alice', age: 30 },
    { id: 2, name: 'Bob', age: 25 },
    { id: 3, name: 'Charlie', age: 35 }
];

// Creating an array of partial objects using Array.prototype.map
const partialObjects = originalArray.map(item => {
    return { id: item.id, name: item.name };
});

console.log(partialObjects);

Output
[
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
]


Similar Reads

Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing reduce MethodUsing Set for Efficient FilteringUsi
3 min read
How to Update an Array of Objects with Another Array of Objects using Lodash?
Updating an array of objects with another array of objects involves merging or updating objects in the first array with corresponding objects from the second array. Below are the approaches to updating an array of objects with another array of objects in the Lodash library: Table of Content Using lodash _.merge() function Using lodash _.mergeWith()
4 min read
How to Create Array of Objects From Keys & Values of Another Object in JavaScript ?
Creating an array of objects from the keys and values of another object involves transforming the key-value pairs of the original object into individual objects within an array. Each object in the array represents a key-value pair from the source object. Below approaches can be used to accomplish this taskTable of Content Using Object.keys() and re
3 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
8 min read
How to Remove Null Objects from Nested Array of objects in JavaScript ?
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed. There are various approaches to
7 min read
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. There are various methods to achieve this separation
5 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below: Table of Content Using filter() with some() methodUsing filter() with includes() methodUsing filter( ) with findIndex() method
7 min read
Extract unique objects by attribute from array of objects
Given an array of objects and the task is to return the unique object by the attribute. Examples: Input: [ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 }, { name: 'Geeks', id: 20 }, { name: 'Geeks', id: 10 } ]Output:[ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 } ]Approach: Let's assume that name is an attribute that di
4 min read
Get list of Duplicate Objects in an Array of Objects
Finding duplicates in an array of objects is a common task in JavaScript, especially when dealing with data manipulation and validation. This will guide you through the process of identifying duplicate objects in an array using various techniques. Understanding the ProblemLet's assume we have an array of objects where each object has a set of key-v
4 min read
How to Convert Object Containing Objects into Array of Objects using Lodash?
Lodash is a JavaScript utility library that provides predefined functions to make code more readable and cleaner. These functions are optimized for performance, often being faster than native JavaScript methods for complex operations.We will learn how to convert an object containing objects into an array of objects using Lodash. There are two appro
4 min read
Difference Between Partial Application and Currying in javascript
Partial ApplicationPartial Application is a technique used to fix or 'partially' apply some of the arguments of a function, creating a new function that expects the remaining arguments. This simplifies function calls and provides greater flexibility, making it easier to reuse and customize functions for specific use cases. Example: In this example,
3 min read
Currying vs Partial Application in JavaScript
Currying and partial application are both techniques used in functional programming languages to manipulate functions. They both involve breaking down functions with multiple arguments into functions that take fewer arguments. However, they have subtle differences in their implementation and applications. Table of Content What is Currying?What is P
4 min read
How to pass array in another array of objects?
In this article, we will try to understand how to pass an array in another array of objects in JavaScript with the help of specific examples. Pre-requisite: Array of Objects in JavaScript Example: Input:[ [ [100, 100, 100], [100, 100, 98, 50], [100, 100, 100, 20], ], [ [100, 100, 100, 99], [100, 100, 100, 100], ],]Output:[ [{ total: 300 }, { total:
4 min read
What is the difference between Host objects and Native objects ?
In this article, we will learn about what are Host objects and Native objects, and their differences. JavaScript objects are broadly classified into 2 categories - native javascript objects and host javascript objects. Native objects: Native javascript objects are standard javascript objects which are provided by javascript itself. They are also kn
2 min read
How to access mapped objects in another function in ReactJS ?
Following is the simple approach to access objects of array.map() to another function in React We can directly call the function in array.map() and pass the object in that function to return the required value. Setting up environment and Execution: Step 1: Create React App command npx create-react-app foldernameStep 2: After creating your project f
2 min read
How to find Objects that Contain the same Elements from Arrays in Another Object ?
To find objects containing identical elements as specified arrays within another object, iterate through the objects. Identify those whose elements match the provided arrays. This involves comparing the presence of identical elements, ensuring all elements from the arrays exist within the target objects. There are various methods to achieve this wh
3 min read
How to find Objects Containing Matching Elements from Arrays in Another Object ?
The task is to find objects that contain matching elements from arrays in another object. An object containing an array of values and a separate object. The objective is to determine whether the values present in the array are also present as keys in the separate object. These are the following methods: Table of Content Using forEach loopUsing filt
4 min read
How to create an array with multiple objects having multiple nested key-value pairs in JavaScript ?
In this article, we will learn to create an array with multiple objects having key-value pairs, we will use nesting which means defining another array in a pre-defined array with key-value pairs. Suppose we have several arrays of objects means containing various key-value pairs where keys are uniquely identified now we have to add these arrays to a
3 min read
How to create an array of objects from multiple arrays in JavaScript ?
Creating an array of objects from multiple arrays in JavaScript involves combining corresponding elements from each array into single objects. This approach allows you to efficiently organize related data from separate arrays into a structured format, making it easier to manipulate and access the combined information. Below are the approaches used
5 min read
Underscore.js _.partial() Function
The _.partial() function is used to apply partially a function by filling in any number of its arguments, without changing its dynamic value. Syntax: _.partial(function, *arguments) Parameters: This function accept two parameters as mentioned above and described below: function: The function that need to be executed. arguments: This parameter needs
1 min read
How to declare a partial border to a box ?
CSS (Cascading Style Sheets) is a stylesheet language used to design a webpage to make it attractive. The reason for using this is to simplify the process of making web pages presentable. It allows you to apply styles on web pages. More importantly, it enables you to do this independent of the HTML that makes up each web page. In this article, we w
2 min read
How to Fix the "partial is not defined" Error in EJS ?
Encountering an error message like "partial is not defined" can be a stumbling block when you're working with EJS (Embedded JavaScript) templates. This error typically pops up when you're trying to use the `partial` function in EJS, but it's not being recognized. Don't worry, though it's a common hiccup for many developers, and we've got you covere
3 min read
How to Fix Error EJS 'partial is not defined'?
This article provides a detailed explanation of the ejs 'partial is not defined' error, detailing various approaches to resolve it, from using native EJS features to creating custom functions. The error 'partial is not defined' occurs in EJS when you use a partial function that hasn't been defined. EJS itself doesn't come with a built-in partial fu
3 min read
How to Use Partial Types in TypeScript ?
Partial types in TypeScript offer a versatile solution for creating new types with a subset of properties from existing types. This feature proves invaluable in scenarios where you need to work with incomplete data structures or define flexible interfaces. Below are the approaches to using partial types in TypeScript Table of Content Using the Part
2 min read
Typescript Partial<Type> Utility Type
The Partial<Type> utility in TypeScript creates a new type by making all properties of an existing type optional. This allows you to create flexible object types where only some properties are required, streamlining code and reducing redundancy when working with complex data structures. What is Partial<Type>?Partial<Type> is a Typ
4 min read
Lodash _.partial() Method
Lodash _.partial() method is used to create a function that invokes the given func function with prepended partials to the arguments it receives. Syntax:_.partial(func, partials);Parameters: func: This parameter holds the function to partially apply the arguments to.partials: This parameter holds the arguments to be applied. It is an optional param
2 min read
How to Create Dynamic Values and Objects in JavaScript?
In JavaScript, you can choose dynamic values or variable names and object names and choose to edit the variable name in the future without accessing the array, Dynamic values and objects in JavaScript allow changing, accessing, or creating values and object properties at runtime for flexibility and adaptability. Below are the approaches to create d
3 min read
How to compare two JavaScript array objects using jQuery/JavaScript ?
In this article, we are given two JavaScript array/array objects and the task is to compare the equality of both array objects. These are the methods to compare two JavaScript array objects: Using jQuery not() methodUse the sort() functionUse JSON.stringify() functionUsing every() and indexOf()Using Lodash _.isEqual() MethodApproach 1: Using jQuery
3 min read
JavaScript Course Objects in JavaScript
We have learned about different Data Types that javascript provides us, most of them primitive in nature. Objects are not primitive in nature and are a bit complex to understand. Everything in javascript is basically an object, and that is the reason why it becomes very important to have a good understanding of what they are. Objects are used to st
4 min read
Difference between Array and Array of Objects in JavaScript
ArrayAn Array is a collection of data and a data structure that is stored in a sequence of memory locations. One can access the elements of an array by calling the index number such as 0, 1, 2, 3, ..., etc. The array can store data types like Integer, Float, String, and Boolean all the primitive data types can be stored in an array. Example: In thi
3 min read