This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 7 years ago.
Below is my code:
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = iaData[i];
loNode.states= [];
}
}
modifyData(laData);
In the Output I can see that [{"fname":"India","states":[]},{"fname":"Germany","states":[]}] the states node is getting appended to the Original Array laData.
Question: How do I prevent "States" node to be appended to the laData?
Solution using Jquery.
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
var modifiedData = [];
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = $.extend(true, {}, iaData[i]); //Doing a Deep copy of the object
loNode.states= [];
modifiedData.push(loNode);
}
return modifiedData;
}
var modifiedData = modifyData(laData);
console.log("Original Data:");
console.log(laData);
console.log("Modified Data");
console.log(modifiedData);
Check your browser console to see the different outputs.
You can see that the output of the initial object does not have states appended to it. and Here is the working JSFiddle
You just have to remove one line:
var laData = [{fname:"India"}, {fname: "Germany"}];
function modifyData(iaData) {
for (var i = 0; i < iaData.length; i += 1) {
var loNode = {};
loNode = iaData[i];
//loNode.states= []; <-- remove this line
}
}
modifyData(laData);
The commented line is the one adding an empty array to your node.
If you remove it, you will get the structure you wants
Related
This question already has answers here:
Remove Object from Array using JavaScript
(32 answers)
Closed 3 years ago.
I am having array of objects defined in javascript and would like to delete values based on object property.
I used below code :
var addedItems = [];
var item = {};
item["TId"] = "";
item["VNo"] = "";
item["IDate"] = "";
item["Rate"] = 22;
item["ItemId"] = 12;
item["Quantity"] = 1;
item["ItemTypeId"] = 3;
addedItems.push(item);
removeValueFromObjectByValue(addedItems,12);
function removeValueFromObjectByValue(jsonObject, value) {
jQuery.each(jsonObject, function (i, val) {
if (val.ItemId == value) // delete index
{
return;
delete jsonObject[i];
return;
}
});
}
Expected Result :
When I remove value, it should give me array with 0 elements.
Actual output :
When I remove value, I am getting array with 1 element and the element value is null.
You can use Object.values and splice. Inside the function create a new copy of the original array using JSON.parse & JSON.stringify so that original array does not get modified. Inside the forEach callback use Object.values which will give an array of values. Then use includes to check if this array created using Object.values contains the parameter passed in the function. If true then remove the element from the copied array using splice
var addedItems = [];
var item = {};
item["TId"] = "";
item["VNo"] = "";
item["IDate"] = "";
item["Rate"] = 22;
item["ItemId"] = 12;
item["Quantity"] = 1;
item["ItemTypeId"] = 3;
addedItems.push(item);
function removeValueFromObjectByValue(arr, num) {
let newArr = JSON.parse(JSON.stringify(arr))
arr.forEach(function(item, index) {
let isNumPresent = Object.values(item).includes(num)
if (isNumPresent) {
newArr.splice(index, 1);
}
})
return newArr;
}
console.log(removeValueFromObjectByValue(addedItems, 12));
I am trying to list all data from Javascript keys Object when I put it in console log there is all information, but when I want to use InnerHTML I keep getting the first object only shown.
function gotData(data){
var scores = data.val();
var keys = Object.keys(scores);
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var pro = scores[k].result;
var doc = document.getElementById("result").innerHTML = pro;
}
}
In this case, it will give me only a result of first element from my Firebase
Thanks
Please check out this stackblitz-demo, looks like your missing one small thing if I am understanding what your expected outcome is.
onClick() {
const scores = [{
'one': 1
}, {
'two': 2
}, {
'three': 3
}, {
'four': 4
}, {
'five': 5
}];
var keys = Object.keys(scores);
for (let i = 0; i < keys.length; i++) {
const k = keys[i];
const pro = scores[k].result;
// here the += is what i think you're missing.
const doc = document.getElementById("example").innerHTML += k;
}
}
The issue is that you are overriding innerHTML each time. Instead, you need to append to the existing innerHTML. Change the last line to...
const doc = document.getElementById("example").appendChild(document.createTextNode(k))
appendChild is also much faster than setting innerHTML
.hasOwnProperty is how to see just your stored values. Does this help?
d = snap.val();
for (var k in d) {
if (d.hasOwnProperty(k)) {
if (isObject(d[k]){
console.log(k, d[k]);
} else {
console.log (k);
}
}
}
function isObject(obj) {
return obj === Object(obj);
}
This question already has an answer here:
Only the last value is being repeated in an array
(1 answer)
Closed 4 years ago.
This is my code, I have pushed the data into data[], but all the data showing the same content which is the last.
var myObj = {};
var data = [];
for (var kl = 0; kl < reportCriteriaIdData.length; kl++) {
myObj["id"] = [myId];
myObj[thisobj.scFilterLabel[0]] = [reportCriteriaIdData[kl].text];
myObj["label"] = [reportCriteriaIdData[kl].text];
myObj["index"] = [kl];
data.push(myObj);
}
You need to initialize an empty object inside the for loop so that each time a new object is created and pushed in the array:
var data = [];
for(var kl = 0; kl< reportCriteriaIdData.length; kl++)
{
//initialize empty object
var myObj = {};
myObj["id"] = [myId];
myObj[thisobj.scFilterLabel[0]] = [reportCriteriaIdData[kl].text];
myObj["label"] = [reportCriteriaIdData[kl].text];
myObj["index"] = [kl];
data.push(myObj);
}
This question already has answers here:
How to get unique values in an array [duplicate]
(20 answers)
Closed 6 years ago.
I have an array
var myArray = ['1','1','2','2','1','3'] // 6 item
Is there any ways I can return the value of 1 and 2 and 3 ONE time when looping?
//example in pseudocode
var getNumber = [];
var count = 0;
var check = 0;
for(var i in myArray)
{
if(getNumber[check] !== myArray[i])
{
getNumber[count] = myArray[i];
count++;
}
else
{
}
}
and advice to follow up my previous code?
thanks
You should use Array.indexOf and Array.push to check and insert values.
var getNumber = [];
for(var i in myArray)
{
if(getNumber.indexOf(myArray[i]) < 0) //See if the number wasn't found already
{
getNumber.push(myArray[i]);
}
else
{
//This number was found before. Do nothing!
}
}
you could do something like :
function leaveDupes(arry){
var newArry = [], keys={};
for(var i in arry){
if(!keys[arry[i]]){
newArry.push(arry[i]);
keys[arry[i]]=true;
}
}
return newArry;
}
console.log(leaveDupes(['1','1','2','2','1','3'] ))
using underscore.js, you can do something like:
newArry = _.uniq(['1','1','2','2','1','3']);
var obj = {};
for (var i = 0; i < myArray.length; i++) {
if (!obj[myArray[i]]) {
obj[myArray[i]] = true;
console.log(myArray[i]); //these are the unique values
}
}
This will work.
var myArray = ['1','1','2','2','1','3']
var getNumber = {};
var retArray = [];
myArray.forEach(function(val){
if(!getNumber[val]){
getNumber[val] = val;
retArray.push(val);
}
});
return retArray
You can use forEach and indexOf array method to find the unique elements.
var myArray = ['1','1','2','2','1','3','4','4','5'];
var uniqueArray =[]; //A new array which will hold unique values
function _unique(myArray){
myArray.forEach(function(item,index){
if(uniqueArray.indexOf(item) ==-1){ //Check if new array contains item
uniqueArray.push(item)
}
})
}
_unique(myArray);
I m new a web developer and i face up the following problem:
"Cannot read property 'length' of undefined"
my code:
var data=();
for(var i;i<parseInt(window.localStorage["numOfInserts"]);i++){
data["category_name"]=localStorage.getItem(("category_name_"+i).toString());
data["category_id"]=localStorage.getItem(("category_id_"+i).toString());
data["provider_name"]=localStorage.getItem(("provider_name_"+i).toString());
data["provider_id"]=localStorage.getItem(("provider_id_"+i).toString());
data["appointment_date"]=localStorage.getItem(("appointment_date_"+i).toString());
data["appointment_time"]=localStorage.getItem(("appointment_time_"+i).toString());
}
$scope.allAppointments=dataArray;
for(var i=0;i<dataArray.length;i++){
$scope.showme[i]=false;
}
After some research I understand that the problem caused to the fact that data is an array but I try to turn it to json, but
var data ={};
gives me the same error as before.
Please Help me
I think this is what you're looking for, see code comments:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array, using the information
// from local storage. Note that you don't need toString() here.
// Once we've created the object (the {...} bit), we push it onto
// the array
data.push({
category_name: localStorage.getItem("category_name_"+i),
category_id: localStorage.getItem("category_id_"+i),
provider_name: localStorage.getItem("provider_name_"+i),
provider_id: localStorage.getItem("provider_id_"+i),
appointment_date: localStorage.getItem("appointment_date_"+i),
appointment_time: localStorage.getItem("appointment_time_"+i)
});
}
This does the same thing, it's just more verbose and so could help you understand more clearly what's going on:
// Create an array using []
var data = [];
// Get the count once
var count = parseInt(window.localStorage["numOfInserts"]);
// Be sure to initialize `i` to 0
for (var i = 0; i < count; i++) {
// Create an object to push onto the array
var obj = {};
// Fill it in from local storage. Note that you don't need toString() here.
obj.category_name = localStorage.getItem("category_name_"+i);
obj.category_id = localStorage.getItem("category_id_"+i);
obj.provider_name = localStorage.getItem("provider_name_"+i);
obj.provider_id = localStorage.getItem("provider_id_"+i);
obj.appointment_date = localStorage.getItem("appointment_date_"+i);
obj.appointment_time = localStorage.getItem("appointment_time_"+i);
// Push the object onto the array
data.push(obj);
}
You need to create an array(dataArray before the loop), and create a new object in each iteration and set the property values for that object then add the object to the array like below
var dataArray = [],
data, numOfInserts = parseInt(window.localStorage["numOfInserts"]);
for (var i = 0; i < numOfInserts; i++) {
data = {};
data["category_name"] = localStorage.getItem(("category_name_" + i).toString());
data["category_id"] = localStorage.getItem(("category_id_" + i).toString());
data["provider_name"] = localStorage.getItem(("provider_name_" + i).toString());
data["provider_id"] = localStorage.getItem(("provider_id_" + i).toString());
data["appointment_date"] = localStorage.getItem(("appointment_date_" + i).toString());
data["appointment_time"] = localStorage.getItem(("appointment_time_" + i).toString());
dataArray.push(data)
}
$scope.allAppointments = dataArray;
for (var i = 0; i < dataArray.length; i++) {
$scope.showme[i] = false;
}
It looks like you're trying to create an associative array, so the first line should indeed be
var data = {};
The next part is fine, but then it looks like you want to enumerate the keys
for(var i=0;i<Object.keys(data).length;i++){
$scope.showme[i]=false;
}