Deleting an element in json array using Javascript - javascript

I want to delete the element from json array using nodejs. My json file match.json is as follows.
[{"id":"1234","time":"3"}]
from this I want to delete the first element so that the json file looks like this:
[]
I tried the following code,its printing an empty array in the console but it is not removing the elements from the match.json file
for(var i=0;i<w;i++)
{
for(var j=0;j<m;j++){
if((words[i].id==match[j].id) && (words[i].time==match[j].time))
{
var f1=0;
//var id1=match[j].id;
var linkadd=words[i].link;
delete match[j];
console.log(match);
}
}
}

Use match.splice(i, 1) instead of delete match[i]

var arr = JSON.parse(Match_json_data);
// remove 1st element
var indexOfItemToRemove = 0;
var noOfItemsToRemove = 1;
arr.splice(indexOfItemToRemove, noOfItemsToRemove);
Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice?v=control

This should work:
let myJsonString = '[{"id":"1234","time":"3"}]';
let myEditedJsonString = JSON.stringify(JSON.parse(myJsonString).shift());

to remove the element..you can use splice.. The element will be removed.
{
var f1=0;
//var id1=match[j].id;
var linkadd=words[i].link;
match.splice(i, 1);
console.log(match);
}
If you use delete match[i], the list becomes [undefined]. So use splice.
So basically delete does not delete the element, rather it sets the element as undefined.

const items = [{"id":"1234","time":"3"}]
console.log('before removing item ==> ', items)
items.splice(0 /*index to be removed*/, 1/*no. of items to be removed*/)
console.log('after removing item ==> ', items)

If you want to always take out the first element and update the array the use the following code.
var arr =[{"id":"1234","time":"3"}]
arr.reverse().pop()
If you want to get a subset of the array you can slice the array but it will not update the array but create a new array.
arr.slice(STARTING_ADDRESS,NO_OF_ELEMENTS_TO_SLICE)
NOTE: This will return a new array, So if you want to update the old array then you need to assign it to the old array.
arr = arr.slice(STARTING_ADDRESS,NO_OF_ELEMENTS_TO_SLICE)

Related

How to get value on class and put into array JavaScript DOM?

I have some tables that have data and can using it on <td>. So more like it I have something like this (show on images below)
My Element
I want to get that all positions Name and put it into an array so I can make of use that array I tried to use this code and got undefined
script.js
/** Checking if There positions name */
function checkPositions(){
let positions = document.getElementsByClassName('check-positions').innerHTML;
let array = [];
array.push(positions);
console.log(array);
}
Then how can I get that value??
The problem that you have is that document.getElementsByClassName('check-positions') returns a HTMLCollection which does not have an innerHTML property.
What you need to do is convert the HTMLCollection into an array, and then read the innerHTML property for each of the items in the array. See the following example:
const elements = document.getElementsByClassName('check-positions');
const positions = Array.from(elements).map(element => element.innerHTML);
console.log(positions);
<div class="check-positions">1</div>
<div class="check-positions">2</div>
<div class="check-positions">3</div>
Use like this
let positions = document.getElementsByClassName('check-positions')[0].innerHTML;
It's showing none because u r fatching whole array and pushing it without using indexes
Code
function checkPositions(){
all_ele = document.getElementsByClassName('check-positions')
length = all_ele.length
let array = [];
for( let i=0;i<length;i++)
{
let positions = document.getElementsByClassName('check-positions')[i].innerHTML;
array.push(positions);
}
console.log(array);
you can use jquery code to do this.
var arr = [];
$("#tablePlacement tr").each(function() {
var name = $(this).children('td.check-positions').text();
arr.push(name);
});
You should use
let positions = document.getElementsByClassName('check-positions').innerText;

appendChild() fails when trying to append a value stored in an array

The following code deletes all children of a certain element, besides these listed inside the saved variable.
let rightCol = document.querySelector("#rightCol");
let saved = rightCol.querySelectorAll('._4-u2._3-96._4-u8');
let savedArr = [];
saved.forEach(()=>{
savedArr.push(saved);
});
rightCol.innerHTML = ''; // Delete all children before retrieving "saved" ones.
for (var i = 0; i < savedArr.length; i++) {
rightCol.appendChild(savedArr[i]);
};
The code fails with this error:
TypeError: Argument 1 of Node.appendChild does not implement interface Node.
Why the code fails?
The code you presented have 2 errors:
querySelectorAll should be executed on document.
you are pushing entire array in for each loop.
here is the working copy
let rightCol = document.querySelector("#rightCol");
let saved = document.querySelectorAll('._4-u2._3-96._4-u8');
let savedArr = [];
saved.forEach((s)=> {
savedArr.push(s);
});
rightCol.innerHTML = ''; // Delete all children before retrieving "saved" ones.
for (var i = 0; i < savedArr.length; i++) {
rightCol.appendChild(savedArr[i]);
};
You are pushing your collection array for each element in your selection return instead of the elements
Where your code state .each(()=> on the next line, the argument to push should be this
On each iteration of forEach you are adding the entire saved array to savedArr. You should instead add each item using the parameter passed into the forEach callback.
e.g.
saved.forEach((s)=> {
savedArr.push(s);
});
Not sure why you're copying the array over to another array here though..

how to find specific objects and put them in an array in javascript

I have this result in my script
'[{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Havana, Cuba"},{"region":"NCA","depprt":"Montego Bay, Jamaica"},{"region":"NCA","depprt":"Montego Bay, Jamaica"}]'
this is the code to get it.
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.stringify(jsonList);
for jsList I got above result.now I want to get all depprt where region is equal to NCA.how can I do that.
You can use the .filter() method for this.
var ncaList = jsonList.filter(function(obj){ return obj.region == "NCA"; });
Very simple. Iterate over the jList array and see if the region property matches your condition or not then append the item to your filtered array.
var filtered = [];
jList.forEach(function(item) {
if(item.region == 'NCA') {
filtered.push(item);
}
});
Just iterate over it:
var filteredDepprts = [];
jsList.forEach(function(element){
if(element.region == 'NCA'){
filteredList.push(element.depprt); //or element if you want to push the full object
}
});
The JSON.stringify method converts a JavaScript value to a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
When you want to convert a JSON string to a JavaScript value, use JSON.parse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
var jsonList = '#Html.Raw(Json.Encode(ViewBag.chk))'
var jsList = JSON.parse(jsonList);
Using single quotes around your #Html.Raw, creates a string and not a JavaScript value. The filter method does not work on strings
Eventually you could use Array.prototype.filter Filter out each element in array, that matches your criteria.
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Try map:
var obj= [];
for (i in jsonList) {
if (jsonList[i].region == "NCA") { obj.push(jsonList[i])};
}
https://jsfiddle.net/pd6hvn78/

store the index based array

Hi I have use the following code snippet to create the array .
var rows = [];
rows["_id1"] = 1;
but in this case 1 did not insert into the array. Is there any other way to achieve this.
Screenshot:
Make it an object.
var rows = {};
rows["_id1"] = 1;
Or if you really want an array, you can have an array of objects
rows.push({"_id1": 1});

Remove an element from find return

With the fallowing code I want to delete the last element inside the steps variable,
var steps = $(element).find("fieldset");
var count = steps.size();
steps[count-1] = null;
but when I iterate with the each method, it doesn't seems to see the null value
steps.each(function(i) {
});
Use the slice function
steps = steps.slice(0, -1);
You could use not() to create a new jQuery object removing the elements you don't want:
steps = steps.not(steps.last());

Categories