Is there a more efficient alternative to using JavaScript JSON?

Is there a quicker method for writing this code efficiently?

view =  + data.items[ 0 ].statistics.viewCount
view1 =  + data.items[ 1 ].statistics.viewCount
view2 =  + data.items[ 2 ].statistics.viewCount
document.getElementById("views").innerHTML = view;
document.getElementById("views2").innerHTML = view1;
document.getElementById("views3").innerHTML = view2; 

Answer №1

Utilizing jQuery to target elements with an attribute that starts with a specific value

var viewCountArr = data.items.map(function(item) {
  return item.statistics.viewCount;
});

var elements = $('[id^="views"]');

$.each(elements, function(index, value) {
  $(this).html(viewCountArr[index]);
});

Answer №2

Below is a revised version with reduced redundancy:

["item1","item2","item3"].forEach(function(val, idx){
  document.getElementById(val).innerHTML = data.items[idx].details;
});

Please keep in mind that using the .forEach method requires ES5 or higher compatibility; if you're working with ES3, consider alternatives such as Underscore's _.each, or other available libraries.

Answer №3

if we assume the structure of your data is similar to this:

var data = {
  items: [
    {statistics: {viewcount: 5}},
    {statistics: {viewcount: 346}},
    {statistics: {viewcount: 123}}
  ]
};

then a possible solution could be:

data.items.map(function(el, i){
  var idx = 'views' + (i > 0 ? i+1 : '');
  document.getElementById(idx).innerHTML = el.statistics.viewcount;
});

Check out the code in JSBin here

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

What is the process to incorporate the OR operator into a Mongoose schema?

I'm currently in the process of developing a website builder using Node.js, allowing users to incorporate various custom components to create their own websites However, I've encountered an issue with my mongoose model when attempting to designa ...

Issue encountered while parsing JSON file using AngularJS

Having some trouble reading a json file in AngularJS using $http.get and encountering errors in the browser console. Check out my Plunker example: http://plnkr.co/edit/SDRpu1MmrTPpgpdb6Kyk?p=preview Below is the code snippet: Javascript:- var jayApp = ...

Group JSON elements based on their values

Good day, I am currently working on creating a JSON file that organizes Portuguese parishes by district, municipality, and parish. The structure I am aiming for is as follows: { "district": "Aveiro", "OfficialCodeDistrict" ...

Various options can be chosen to alter the margin

$('#cpseltop').change(function() { var a = $(this).val(); $('.cpselhide').hide(); $('#cpsel' + a).show(); }); .cpselect{ display:block; border:1px solid #999; border-radius:9px; outline:none; width:100%; padding:2px 5px; curso ...

Is Three.js application compatible with mobile browsers?

I'm working on an application that relies on the Three.js library. Unfortunately, I've run into an issue where it doesn't seem to work on mobile browsers when using WebGLRender. I've looked at some applications created by Mr.doob () for ...

In Node.js using Express, you can set up a validator to require a field only if another specific

Currently, I am utilizing express-validator to validate my post fields. However, I am facing an issue where I need certain fields to be required only if other fields have specific values. For example: If the person_organisation field is true: The person_o ...

How to Target HTML Tags Locally using CSS Modules in Next.js?

I am looking to implement smooth scrolling specifically on one page in my Next.js application, such as my blog. Instead of applying it to the entire site through the globals.css file, I need a way to inject scroll-behavior: smooth; into the html tag only f ...

Creating a hierarchical tree structure in AngularJS by recursively traversing JSON data

I am having trouble creating a node tree from a JSON file. My index.html file should load the node tree recursively from person.json, but I'm stuck in an infinite loop. Can someone please assist me with this? app.js (function() { var app = angula ...

Converting a string array to an array object in JavaScript: A step-by-step guide

My task involves extracting an array from a string and manipulating its objects. var arrayString = "[{'name': 'Ruwaida Abdo'}, {'name': 'Najlaa Saadi'}]"; This scenario arises when working with a JSON file where ce ...

``Utilizing jQuery for real-time validation of input fields`

I dynamically add two fields, one for reference link and the other for reference text, in a jQuery modal dialog that pops up when "add user" is clicked. Users can add or delete these fields as needed. Here is the code I used to accomplish this: var $ctrl ...

What steps can I take in JavaScript to assign a value of 0 to values[1] in order to prevent receiving NaN as the output

I'm currently working on a program that calculates the sum of 6 input values, but I've encountered an issue where if a value is missing (for example, only providing 5 values), the result becomes NaN. I attempted to address this by assigning empty ...

Convert the values from the table cells into an array

Recently, I've been working with jQuery to extract an array from table cells, format the data, and pass it into a JavaScript function. The code snippet I have implemented is as follows: var l1 = new Array(); $('table#datatable tbody td:firs ...

Randomize the array of images in Nuxt every time the page is reloaded to display a variety of logos in the carousel

I've set up a carousel of logos, with the intention to randomize their order every time the page reloads. The challenge is that my layout only allows for 10 images to be displayed at once. While it seems like everything is functioning correctly, I&ap ...

What is the best way to send a parameter from JavaScript to a UserControl?

Within my ASP.Net application, I have a UserControl named EmployeesUserControl that is displayed within a JQuery modal dialog. Prior to displaying the Employees, I need to provide a filter criteria indicating which entity the employee belongs to. My query ...

Repairing my CSS with jQuery fullpage.js

My CSS on needs fixing. The word Obert is not aligning properly in the section. Interestingly, everything works fine without Javascript: I suspect the wrapper divs created by the plugin are causing the issue. Can someone lend a hand, please? ...

Retrieve the string saved in a ViewBag when the ajax call is successful

I am new to ASP.NET MVC and have been struggling to find a solution to this problem. Despite searching on various platforms, including Stack Overflow, I have not been able to resolve it. Here are some links to solutions that did not work for me: Possible ...

Is it possible to create a compound editor within a cell in SlickGrid that contains two date fields

Currently, I am implementing SlickGrid with jQuery and I am interested in incorporating a compound editor within a cell similar to example 3a mentioned here. However, instead of two text fields, I would like to have two date fields. Although Example 3 dem ...

Modifying a Json file in a Node application, while retaining the previously stored data

In my node script, I have a simple process where I update the db.json file via a form. The file is successfully updated, but when I try to render it in response for a GET or POST request, it only shows the previous results. var cors = require('cors&ap ...

Converting a JSON object to a class in ASP.NET MVC - A step-by-step guide

Having trouble converting the JSON object below to a class in Asp.Net MVC. { "Name.Test":"fsafasfda" } If you have any suggestions, they are greatly appreciated. The situation is as follows in an ASP.NET action: [HttpPut] public JsonResult Te ...

Ways to repair the error message: "Unable to access property 'clientWidth' of undefined"

Whenever I resize the window, I encounter an error stating "Cannot read property 'clientWidth' of null". It appears to be related to the fact that the ref is null. Do you have any suggestions on how to troubleshoot this issue? import React, { us ...