Generate the entity and then transfer the data into an array

I am dealing with multi-level hierarchies that need to be displayed in a select list. Once the user selects values from the table column, they should be able to filter by clicking on the column.

var name = ['Akansha', 'Navya'];
var age = ['24', '26'];
var id = ['2345', '34555'];

These values must be passed in JSON format for filtering purposes. To achieve this, we need to follow a specific hierarchy to structure the data correctly.

Values: Array(2)

We need to create an array based on the predefined JSON format that includes the necessary values.

Values: (2)
0: {name: 'Akansha', age: '24', id: '2345'}
1: {name: 'Navya', age: '26', id: '34555'}

To generate the required array list, I have used a loop to iterate through the values.

var nameValues = [];
for(var i=0; i < name.length; i++){
 var filterValue = new nam3({
   name: name[i],
   age: age[i],
   id: id[i]
 });
 nameValues.push(filterValue);
}
console.log(nameValues); // This provides the desired array list with formatted values.
// (2)
// 0: {name: 'Akansha', age: '24', id: '2345'}
// 1: {name: 'Navya', age: '26', id: '34555'}

Next, I need to push these name values into the product filter. The filter ID is 'product'.

product.values.push(nameValues);

However, when pushing the data, it creates a nested array causing an object reference error. The output does not match the required format.

Values: Array(1)
       0: Array(2)
          0: {name: 'Akansha', age: '24', id: '2345'}
          1: {name: 'Navya', age: '26', id: '34555'}

The expected output should be:

Values: (2)
0: {name: 'Akansha', age: '24', id: '2345'}
1: {name: 'Navya', age: '26', id: '34555'}

I am having difficulty passing the name values into the correct place within the JSON array. Any assistance would be greatly appreciated as I am relatively new to JavaScript and troubleshooting this issue.

Answer №1

there are different ways to merge arrays in JavaScript

const arr1 = [{name:'John', age:'30', id:'1234'},
{name:'Emma', age:'27', id:'5678'}]

const arrayToMerge = {items: [{name:'Jane', age:'28', id:'8765'}]}
arrayToMerge.items = arrayToMerge.items.concat(arr1)

console.log(arrayToMerge.items)

const arrayToMerge2 = {items: [{name:'Jane', age:'28', id:'8765'}]}

arrayToMerge2.items = [...arrayToMerge2.items,...arr1]

console.log(arrayToMerge2.items)

const arrayToMerge3 = {items: [{name:'Jane', age:'28', id:'8765'}]}

arrayToMerge3.items.push(...arr1)

console.log(arrayToMerge3.items)

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

Comparing a series of smaller strings to a larger string for testing purposes

My website has an array filled with bot names. Whenever a user or bot visits the site, I retrieve the user-agent and want to check if any of the values in my array are present in it. var bots = [ "twitterbot", "linkedinbot", "facebookexternalhit", ...

Obtaining values from event listeners in Vue.js across different methods

Looking for guidance on the code snippet provided below. Is there a way to assign the value of "e.detail.name" to "nodeName," and then access it in a different method within the component for an API request? data() { return { nodeName: '' ...

What is the correct method to remove an item from local storage?

Using localStorage, I have stored multiple objects in an array. Is there a way to remove just one object from this array? If I use localstorage.removeItem(keysofthelocalstorage), I can delete the entire array, but I specifically want to remove only certai ...

jq: Leveraging streams instead of "not"

It seems like a rather simple issue, but I just can't seem to solve it. My goal is to extract some data using the --stream option of jq based on this question. Here's a snippet of my JSON dataset: { "date": "2023-07-30", & ...

Using AngularJS to Retrieve a Specific DOM Element Using its Unique Identifier

Example Please take a look at this Plunkr example. Requirement I am looking for a way to retrieve an element by its id. The provided code should be capable of applying a CSS class to any existing DOM element within the current view. This functionality ...

Make window.print() trigger the download of a PDF file

Recently, I added a new feature to my website allowing users to download the site's content by following these instructions: Printing with Javascript || Mozilla Dev. Essentially, the user can print a newly formatted site stored in a hidden iframe. Now ...

Access a JSON file in the Resources directory using JsonObject

Looking for assistance on how to assign the JSON file within Resources to an instance of JsonObject and then parse it. MainActivicy: boolean bool = true; boolean bool2=true; String s = ""; input = getResources().openRawResource(R.raw.info ...

Difficulty transferring form information to PHP utilizing Ajax

Originally, I had a traditional HTML form that submitted data through a button, redirecting the user to the page where the PHP code ran successfully. Now that everything is functioning as expected, I aim to pass the form variables to PHP using Ajax in ord ...

I am encountering a problem where I lose the values of a nested array of objects when trying to push it into another array

My goal is to format data for use with the amCharts library. The required structure should look like this: data = [{ name: "First", total: 190, children: [ { name: "A1", value: 100 }, { name: &q ...

How to trigger an Angular JS route without loading a view

Could someone help me with calling the /auth/logout url to get redirected after a session is deleted? app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/auth/logout',{ controller:'AuthLo ...

Using Jquery to target an element within the same DOM element and apply changes

My website platform doesn't assign any IDs or classes to the menus it generates, and uses nested lists for submenus. To make the submenus expand upon clicking, I created a jQuery script: $(function () { $(".wrapper ul li").click(function () { ...

combine object with an array attribute

If we have the following objects: let firstObject = {items: ["apple"]}; let secondObject = {items: ["orange"]}; and then execute Object.assign(firstObject, secondObject); the new state will be: firstObject.items[0] //"orange" firstObject.items === sec ...

Convert a Ruby string into a JSON formatted string

When working with the json gem, I ran into an issue where directly encoding strings to their JSON representation was not possible. To solve this problem, I tried adapting some PHP code: $text = json_encode($string); into Ruby like this: text = string.in ...

Sending an integer through an AJAX request without relying on jQuery:

I am having trouble sending an integer named 'petadid' from my JavaScript to the Django view called 'petadlikeview'. The data doesn't seem to be reaching the view, as when I print 'petadid' in the view it displays as &apo ...

Error: Unable to execute map() function on commands.options? while configuring slash commands

discord js v13.3.1 I have configured my bot to update and deploy slash commands using a specific command called "deploy". The structure of the deploy command is as follows: module.exports = { name: "deploy", description: "deploys sl ...

Error: The react.js application is unable to access the property 'classList' of a null object

I've encountered a bug that's been causing me some trouble. Every time I try to run my react application, I keep getting an error message that reads TypeError: Cannot read property 'classList' of null. As someone who is new to react, I& ...

How does the 'this' variable function when it comes to models in embedded documents?

Being relatively new to node.js and sails, I find it quite easy to work with and enjoy it :) Currently, I am using the sails Framework version 0.10rc3 with MongoDB and sails-mongo. I understand that the contributors of waterline do not particularly like e ...

What is the best way to extract data from a JSON object in JavaScript?

let result = JSON.parse(data.d); The current code doesn't seem to be working.. Here is the structure of my JSON object: [{"ItemId":1,"ItemName":"Sizzler"},{"ItemId":2,"ItemName":"Starter"},{"ItemId":3,"ItemName":"Salad"}] Any suggestions on how I ...

Adding a value to an element in JavaScript to interact with it using Selenium

After implementing the provided code snippet, I noticed that it replaces the value in the element with a new one. However, I am looking to append or insert a new line rather than just replacing the existing value. Is there an alternative command like app ...

The ajax success() function is failing to function properly when attempting to make a call

The button's onClick() event is not navigating anywhere. There seems to be an issue with the success() function of the ajax call. Unfortunately, I am new to this and unable to pinpoint the problem. var currentAuthor=""; var currentQuote=""; $(documen ...