How to insert a JSON object into a nested array using JavaScript

I am currently facing an issue with adding a JSON object based on specific conditions to an array, which is then used to create a WINJSList. The problem arises when I try to access the elements of the list or array after using the array.push method. My goal is to verify that the additions are being done correctly. Any assistance on this matter would be highly appreciated. Here is the code snippet:

var names_Array = new Array;                
var names_List = new WinJS.Binding.List(names_Array);

if (condition) {
  if (condition) {
    names_List.push({ 
      name: "Joe Dowling", 
      image: "image/Joe Dowling.png", 
      ClientID: "1234" 
    });
  } else if (condition) {
    names_List.push({
      name: "Esteban Flamenco ", 
      image: "image/Esteban Flamenco.png", 
      ClientID: "6666" 
    });
  } else if (condition) {
    names_List.push({ 
      name: "Plain Jane ", 
      image: "image/Plain Jane.png", 
      ClientID: "0000" 
    });
                        }
console.log(names_Array);
console.log(names_Array[0]);
console.log(names_List);
console.log(names_List[0]);

I have also attempted:

var names_Array = new Array; 
if (condition) { 
  if (condition) {
    names_Array.push({
      name: "Joe Dowling", 
      image: "image/Joe Dowling.png", 
      ClientID: "1234" 
    });
  } else if (condition) {
    names_Array.push({
      name: "Esteban Flamenco ", 
      image: "image/Esteban Flamenco.png", 
      ClientID: "6666" 
    });
  } else if (condition) {
    names_Array.push({ 
      name: "Plain Jane ", 
      image: "image/Plain Jane.png", 
      ClientID: "0000" 
    });
  }

  var names_List = new WinJS.Binding.List(names_Array);

When checking the console, I encounter issues where I either see undefined or [object object].

Answer №1

To learn more about WinJS.Binding.List, please consult the documentation here.

There are a few issues with the code:

  • The WinJS List initializes itself with the array provided to the constructor. If the array is modified afterwards, the changes do not automatically reflect on the WinJS list.
  • To access an element at a specific index, use list.getAt(index)

This revised code snippet should function correctly:

var data = []; 
data.push({
    name: "Joe Dowling",
    image: "image/Joe Dowling.png",
    ClientID: "1234"
});
data.push({
    name: "Esteban Flamenco ",
    image: "image/Esteban Flamenco.png",
    ClientID: "6666"
        });
data.push({
    name: "Plain Jane ",
    image: "image/Plain Jane.png",
    ClientID: "0000"
});

var list = new WinJS.Binding.List(data);
var item = list.getAt(0);
console.info(JSON.stringify(item))

Answer №2

Here's a straightforward illustration based on the data you're working with, to simplify things:

const myData = []; 
myData.push({ 
      name: "Sam Davidson", 
      image: "image/Sam Davidson.png", 
      ClientID: "5678" 
    });
myData.push({
      name: "Sara Smith ", 
      image: "image/Sara Smith.png", 
      ClientID: "9999" 
    });
myData.push({ 
      name: "Robert Johnson ", 
      image: "image/Robert Johnson.png", 
      ClientID: "4321" 
    });


<!-- let item = myData.find(data => data.ClientID === '5678') -->
console.log(JSON.stringify(myData))
console.log(JSON.stringify(myData[0]))
let selectedData = myData[0];

for(let key in selectedData){
    console.log(key); //key
    console.log(selectedData[key]); //value
}

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

Capture user input to extract data from a JavaScript object

I need help with implementing a search function where users can enter a name and the person's extension will be displayed on the UI either by clicking a button or pressing "return". Any ideas on how to make this feature work seamlessly? UI <html ...

Getting the most out of setInterval() - a guide in jQuery

I am currently working on an auto slide feature and could use some guidance with setInterval(). From my understanding, setInterval() is used to repeat functions infinitely, which is exactly what I need for this project. Here is the current layout: HTML & ...

Creating a personalized input slider: A step-by-step guide

I have a question about how to design a custom input slider with the label inside the field itself. The desired output should look like the screenshot below: https://i.sstatic.net/gE6EJ.png I have successfully created the input field part, but I am stru ...

A guide to leveraging Mongoose transactions when utilizing the updateMany method

While utilizing the mongoose updateMany() method within a transaction, I encountered some confusion. The documentation provides an example of using save() with a session, such as Model.save({session: mySession}), but I am unsure how to apply this to Model. ...

Ways to refresh UI in ReactJS without triggering a specific event

In my React application, I am displaying various pictures and GIFs that users can attach to a post. Currently, each image has an onClick handler which triggers either a modal with different options or deletes the picture if the user holds down the ctrl key ...

Uploading with Javascript CORS consistently ends with an error event occurring

My current challenge is uploading a file to a server using JavaScript in compliance with the CORS specification. While there are numerous examples available online that successfully upload the file, I encounter an error as the final event being fired. Up ...

The active tabs or placeholders do not update properly when I click on them

Is there anyone who can help figure out why the tabs are not functioning as expected? The goal is for the tabs to change the input field placeholder and perform a search based on the active tab. If you're able to assist, please review my complete cod ...

Keep duplicating a single object until it fills up the entire screen

Is there a way to make an HTML/CSS element repeat until it covers the entire screen height, without repeating it indefinitely? #container{ height: 100vh; width: 100vw; } .dotts{ background-color: yellow; border-radius: 50%; height: 20px; width: 20p ...

Extract numerical values from a specific area and manipulate them

I'm facing an issue with a field that receives its input from a list of links associated with numbers, similar to a calculator but without operators. My goal is to retrieve these numbers and divide them by 12 using a function (converting from feet to ...

what is the process for configuring a Universal link using javascript?

I have taken all the necessary steps to utilize a universal link. I created an AASA file, verified it using aasa-validator, and configured it in XCODE as required. Now, I am facing the challenge of setting up a hyperlink on my webpage that can redirect us ...

Leverage the power of Laravel and ReactJS to beautifully display images

Currently, I am working on a project where I am incorporating ReactJS into a Laravel blade file. To get started, I included the React CDN and began writing code within the script tag. Everything seems to be going smoothly so far, however, I have encountere ...

Keyboard input that allows for diagonal movement in games at the same time

Currently, I am developing a 2D game using Node where the character must move diagonally. This game is top-down and text-based, existing solely within a Node environment without traditional browser features like keydown/keyup events. To handle user input, ...

The Angular Http Interceptor is failing to trigger a new request after refreshing the token

In my project, I implemented an HTTP interceptor that manages access token refreshing. If a user's access token expires and the request receives a 401 error, this function is designed to handle the situation by refreshing the token and re-executing ...

Guide to importing an ES module in Node.js without specifying a file extension

There's a common belief that when importing ES modules, you should always include a file extension. However, I stumbled upon certain Node projects that seem to import ES modules without an extension, as seen in this particular example. This has left ...

Building an Empty AngularJS Response with the Combination of Spring Boot and MongoDB

In my AngularJS application, I collect user input and store it in painting objects. These objects are then sent to my Spring Boot backend which saves them to a MongoDB server and returns an ID. However, when attempting to POST data to the server, I receive ...

What is the reason for the continued slicing of a numpy array when assigned to a new variable?

Lately, I've been noticing some peculiar behavior while working with numpy arrays. Take a look at the code snippet below: import numpy as np # 1 a = [np.arange(16)] b = a print(f'b = {b}') # 2 b[0] = a[0][::2] print(f'b = {b}') ...

Sending a parameter as text from .NET code-behind to a JavaScript function

So here's the situation: I have a gridview that is displayed in a new window separate from the parent window. This gridview contains multiple records, each with a "view" button that allows users to see more details about the record within the same new ...

The art of positioning images and creatively cropping

Seeking advice on allowing users to dynamically position and clip an image on a webpage. I've tried using CSS and JavaScript for clipping and resizing, but it's not working as expected. If PHP could provide a solution, that would be ideal for my ...

What is the best way to create a self-referencing <div> in HTML?

After extensive research, I turn to seeking advice and guidance on Stack Exchange. I have a seemingly straightforward goal in mind. I want to create a <div> id/class that will automatically generate a link to itself using scripting of some sort. Be ...

Tips for modifying the JSON format within a Spring and Angular project

I am utilizing Spring for the backend and Angular for the frontend. Below is my REST code: @GetMapping(path = "/endpoint") public @ResponseBody Iterable<Relations> getGraphGivenEndpointId(@RequestParam(value = "id") int id) { return ...