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

List of objects showing the Node Output retrieved from a MongoDB database

{ "dependencies" : [ { "name" : "async", "version" : "2.6.1" }, { "name" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8be9e4eff2a6fbeaf9f8eef9cbbaa5bab3a5b8"& ...

Utilize Angular to transform a standard text string within a JSON object into a properly formatted URL

Welcome to my first Stack Overflow question! I usually find the answers I need on my own, but this time I could use some guidance as I delve into Angular. I have a directive that pulls the name and URL from a JSON object and generates HTML with the name a ...

Is there a way for me to provide the product ID based on the selected product?

Is there a way to store the IDs of selected products in a dynamic form with multiple product options? I am able to see the saved products in the console.log(fields, "fields");, but how can I also save the selected product IDs? Any guidance on th ...

Conceal a row in a table using knockout's style binding functionality

Is it possible to bind the display style of a table row using knockout.js with a viewmodel property? I need to utilize this binding in order to toggle the visibility of the table row based on other properties within my viewmodel. Here is an example of HTM ...

Navigating the Basics: Understanding the Four Quadrant Selection Grid in a Material UI & React Pop-Up Form

Sorry if these questions seem silly. I'm diving into React & Material-UI without a mentor to guide me, relying on documentation and tutorials. Is there a better place for quick beginner questions? Maybe a chat forum or Slack group? Not sure if Stack i ...

Modifying the image source using state management in ReactJS

I am currently working on creating an Image slider similar to an e-commerce product in Reactjs. In regular javascript, changing the image source is straightforward, but how do we accomplish this in React? Since React involves dealing with state, it adds a ...

Is there a way to incorporate a component into Particle.js?

I attempted to encase the Particle around the component but it's not functioning correctly import React from "react"; import { render } from "react-dom"; import Particles from "./Particles"; import "./index.css" ...

What is the best way to create shared scope and transmit data within an Angular directive?

In my angular directive, I have the following code: app.directive('myDir', function () { return { restrict: 'E', scope: true, template:'<div>{{myindex}}</div>', link: function(scope, element, att ...

Having trouble getting my list items to display on individual lines within the foreach loop. It just doesn't seem to be working as expected

In the event listener, I need to ensure that my list items within the forEach loop are not displaying on separate lines. This issue is causing a problem in a lengthy section of code. The goal is to update questions when an answer is clicked from a list. B ...

Get the png image file and display a preview of it

Within my template, I have an img tag that is linked to a state known as "imageBuffer" <img v-bind:src="imageBuffer" alt="" /> In the logic of the page, there are two file inputs and I've utilized a single function to manag ...

Execute javascript code 1.6 seconds following the most recent key release

Is there a more efficient way to execute JS 1.6 after a keyup event, considering that the timer should reset if another keyup event occurs within 1.6 seconds? One possible approach could involve utilizing a flag variable like this: var waiting = false; $ ...

Converting a JSON array to an array using SwiftyJSON

I'm dealing with a JSON array named var array: [JSON] = []. I want to convert this into a standard array in order to filter and manipulate the data. Can anyone suggest the best approach for achieving this? One attempt I made was using let filteredArr ...

Is it possible to optimize the performance of my React and TypeScript project with the help of webpack?

I am working on a massive project that takes 6 to 8 minutes to load when I run npm start. Is there a way to speed up the loading process by first displaying the sign-in page and then loading everything else? ...

Getting JSON Data Using Django's get_or_create

As a self-taught programmer exploring Python and Django, I am eager to optimize my code. One challenge I have encountered is performing a get_or_create operation with JSON data that directly correlates to my model entries. data=json.load(file) Person.objec ...

Reproducing a table row

Here is the table structure I am working with: <table id="customFields" class="table table-bordered table-hover additionalMargin alignment"> <thead> <tr> <th colspan="2"></th> <th>Some Title</ ...

Executing Basic Calculations Instantly with Live Data in Qualtrics

I am encountering an issue with displaying the values on a slider in Qualtrics. I need to show the value where the respondent has placed the handle, as well as the complementary value from the other end of the scale. For example, if the user has chosen 55, ...

Unraveling deeply nested array objects in JSON with Java Script/jQuery

I need help working with a JSON file that looks like the following: {[ {"name":"avc"}, {"name":"Anna"}, {"name":"Peter"}, {"Folder":[ {"name":"John"}, {"name":"Anna"}, {"Folder":[ {"name":"gg"}, ...

Executing a simulated onClick event in jQuery

Attempting to create a simulated onclick event on a drop-down menu has proved challenging for me. An IE object is being used to navigate to a page, where I need to modify a dropdown menu that contains an onchange event: $('select[name="blah"]') ...

JQuery not refreshing data values

function addToRewardDatabase() { var rewardValue = "98"; $.post("db/mkreward.php", { proid: getURLParameter("id") }, function(data) { rewardValue = "99"; alert(rewardValue); }); alert(rewardValue); return ...

JavaScript button mouse enter

There seems to be an issue with this code. The button is not functioning properly after hovering over it, even though it was copied from the instructional website where it works fine. <html> <head> <title>Button Magic</t ...