How to pass array in another array of objects?
Last Updated :
12 Jul, 2024
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: 348 }, { total: 320 }],
[{ total: 399 }, { total: 400 }]
]
Below are the approaches to pass an array in another array of objects:
- Create a temporary array result variable.
- Traverse array using forEach() loop and inside it create another temporary array for storing values and thus using that inner values calculate some for each corresponding rows and then add them as another object.
- Display that array of object as an output.
Example: Here we first need to traverse over Arrays of Arrays and then for each array’s values we need to calculate a sum for each array’s corresponding rows.
JavaScript
let numbers_array = [
[
[100, 100, 100],
[100, 100, 98, 50],
[100, 100, 100, 20],
],
[
[100, 100, 100, 99],
[100, 100, 100, 100],
],
];
let desired_output = (numbers_array) => {
let result = [];
numbers_array.forEach((element) => {
let sumCalc = [];
element.forEach((item) => {
let sum = 0;
item.map((value) => {
sum += value;
});
sumCalc.push({ total: sum });
});
result.push(sumCalc);
});
return result;
};
console.log(desired_output(numbers_array));
Output[
[ { total: 300 }, { total: 348 }, { total: 320 } ],
[ { total: 399 }, { total: 400 } ]
]
- In this approach, we will use the map() method which is used in order to traverse over the main array.
- Thereafter reduce() method is used in order to reduce the value as a sum for the output itself.
- Then we will push the sum or total value in as key-value pair in the object and later we will return the object.
Example: Below is the implementation of the above approach.
JavaScript
let numbers_array = [
[
[100, 100, 100],
[100, 100, 98, 50],
[100, 100, 100, 20],
],
[
[100, 100, 100, 99],
[100, 100, 100, 100],
],
];
let desired_output = (numbers_array) => {
let data = numbers_array.map((item) =>
item.map((row) => {
let total_value = row.reduce(
(previous_value, current_value) =>
previous_value + current_value,
0
);
return { total: total_value };
})
);
return data;
};
console.log(desired_output(numbers_array));
Output[
[ { total: 300 }, { total: 348 }, { total: 320 } ],
[ { total: 399 }, { total: 400 } ]
]
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array.
Example:
JavaScript
const arr1 = [1, 2, 3];
const arr2 = ['a', 'b', 'c'];
const newArray = [
{ id: 1, name: 'Object 1', values: [...arr1] },
{ id: 2, name: 'Object 2', values: [...arr2] }
];
console.log(newArray);
Output[
{ id: 1, name: 'Object 1', values: [ 1, 2, 3 ] },
{ id: 2, name: 'Object 2', values: [ 'a', 'b', 'c' ] }
]
Using a loop
Using a loop to pass an array into an array of objects involves iterating through a range and pushing objects into the array. Each object contains the original array (spread operator used to create a copy) as one of its properties.
Example:
JavaScript
let originalArray = [1, 2, 3];
let objectsArray = [];
for (let i = 1; i <= 2; i++) {
objectsArray.push({ id: i, values: [...originalArray] });
}
console.log(objectsArray);
Output[ { id: 1, values: [ 1, 2, 3 ] }, { id: 2, values: [ 1, 2, 3 ] } ]
Method 4: Using map() and Object.entries()
In this approach, we use map() along with Object.entries() to iterate over the main array of arrays. For each inner array, we compute the sum of its elements and then format the result into an object with a specific structure.
Example: Using map() and Object.entries() to format the array of arrays into an array of objects.
JavaScript
const input = [
[
[100, 100, 100],
[100, 100, 98, 50],
[100, 100, 100, 20],
],
[
[100, 100, 100, 99],
[100, 100, 100, 100],
],
];
const result = input.map(array => {
return array.map(innerArray => {
const total = innerArray.reduce((acc, val) => acc + val, 0);
return { total };
});
});
console.log(result);
Output[
[ { total: 300 }, { total: 348 }, { total: 320 } ],
[ { total: 399 }, { total: 400 } ]
]
Similar Reads
How to filter an array of objects in ES6 ?
In this article, we will try to understand how we could filter out or separate certain data from the array of objects in ES6. Let us first try to understand how we could create an array of objects by following certain syntax provided by JavaScript. Table of Content Javascript Array of ObjectsJavascr
4 min read
How to Convert an Array of Objects into an Array of Arrays ?
An Array of objects is an array that contains multiple objects as its elements which can be converted into an array of arrays i.e. an array that contains multiple arrays as its elements. There are several methods listed below to achieve this task. Table of Content Using Object.keys() and Object.valu
3 min read
How To Render An Array Of Objects In ReactJS?
Rendering dynamic data in ReactJS is one of the most fundamental tasks when building interactive web applications. One of the most common scenarios is rendering an array of objects, such as a list of users, products, or posts, in the user interface (UI). To render an array of objects in React we wil
4 min read
How to create an Array of Objects in the Stack memory?
What is an Array of Objects? An array of objects is a data structure that stores a collection of objects of the same type. The objects in the array are stored in contiguous memory locations, and the array provides indexed access to the objects. This means that you can access an individual object in
6 min read
JavaScript - Create Partial Objects Array from Another Array
Here are the different ways to create an array of partial objects from another array in JavaScript 1. Using map()The map() method is the most efficient and commonly used way to extract specific properties from objects in an array. It creates a new array by transforming each object. [GFGTABS] JavaScr
4 min read
Copy Array Items Into Another Array in JavaScript
In JavaScript, copying array items into another array in JavaScript is helpful when you want to make changes to the data without affecting the original array. It helps avoid mistakes, keeps the original data safe, and is useful when you need to work with a separate copy of the array for testing or p
5 min read
How can I Define an Array of Objects in TypeScript?
In TypeScript, the way of defining the arrays of objects is different from JavaScript. Because we need to explicitly type the array at the time of declaration that it will be an Array of objects. In this article, we will discuss the different methods for declaring an array of objects in TypeScript.
6 min read
Sort An Array Of Arrays In JavaScript
The following approaches can be used to sort array of arrays in JavaScript. 1. Using array.sort() Method- Mostly UsedJS array.sort() is used to sort and update the original array in ascending order. [GFGTABS] JavaScript let arr = [[3, 2], [1, 4], [2, 5], [2, 0]]; arr.sort(); console.log(arr); [/GFGT
2 min read
How to use forEach with an Array of Objects in JavaScript ?
Using the forEach() method with an array of objects in JavaScript is essential for iterating over collections and performing operations on each object. This guide explores effective techniques to utilize forEach() for array manipulation, enhancing your coding skills. Syntax: array.forEach( function(
3 min read
How to copy properties from one object to another in ES6 ?
The properties of one object can be copied into another object through different methods. Here are some of those methods. Object.assign(): By using the Object.assign() method, all enumerable properties of one or more source objects are copied to the target object. This method returns the modified ta
3 min read