Currently trying to build a javascript form that converts the inputs into JSON. I've managed to create objects that allow multiple keys/values to be entered however I'm struggling to get my head around the logic and code for nesting a child object within an object.
let objects = [];
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn2').addEventListener('click', function(e) {
e.preventDefault();
let infoBoxOne = document.getElementById('key').value // store the key into a variable
let infoBoxTwo = document.getElementById('value').value // store the value into a variable
const lastObject = objects[objects.length-1] // finds the last object in the objects array
const objectValues = Object.entries(lastObject) // gets all the keys and values
const lastKeyValuePair = values[values.length-1]; // stores the last key and value entered into a variable
})
})
So my initial idea was to find the last key/value within the last object that was added and use something like Object.create() or push() to insert the data. Is there an easier way of achieving this?
edit: here's a jsfiddle showing what I have exactly so far https://jsfiddle.net/9jrzLxnm/
Secone edit: idea of what I'm trying to achieve
{
{
"firstObject":'FirstObject'
},
{
"lastObject": {
"infoBoxOne": "JlastObject",
},
}
}
Ok firstly you have to set the desired location to place a child object as an object itself.. then the rest is intuitive
My example is on jsfiddle
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn2').addEventListener('click', function(e) {
e.preventDefault();
let childKey = document.getElementById('key').value // store the key into a variable
let childValue = document.getElementById('value').value // store the value into a variable
const lastObject = objects[objects.length-1] // finds the last object in the objects array
const values = Object.entries(lastObject) // gets all the keys and values
const [key,value] = values[values.length-1]; // stores the last key and value entered into a variable
lastObject[key]={} //turning place to put child into an object
lastObject[key][childKey]=childValue //placing the nested child
document.forms[0].reset();
listToJson();
})
})
Related
i want to pull data from a .csv file and pass this data to a function to format every row of the .csv file to be a single object. These objects are then stored in an array called "list". So far so good. This is all working.
Next i want a button that calls a function onclick called "roll" that takes a random index from the "list" array and saves an instance of the random oject in a temporarily variable called randomItem.
Then i want to check certain properties of randomItem for specific values and if a certain condition is met it should change a specific property called "randomItem.Name". Finally i want the altered "randomItem" to be pushed into a new array called "results". These results are then being displayed on the website.
If I change the propertys value with "randomItem.Name = randomItem.Name + 'someString'" it also overwrites the original object in the "list" array. I dont want it to do this as i want to repeat the process of rolling random objects from this list several times. Therefor i need the "list" array to keep its original state. I cant get my head around why it overwrites the any list.
html
<button id="btnItem1">Roll</button>
js
$(document).ready(function() {
let list = [];
let results = [];
$('#btnItem1').click({slotName:'item1', listName:list, index:0}, roll);
// i need to pass slotName, listName and index because i have several buttons and list in the real project
getData('data.csv').then(data => formatData(data)); // get data from csv files
async function getData(url) {
const response = await fetch(url);
const data = await response.text();
return data;
};
function formatData(data) { // real formatting function taken out for stackflow
let formatted = // some formatting stuff;
list.push(formatted);
};
function roll(options) {
const slot = options.data.slotName;
const listTemp = options.data.listName;
const index = options.data.index;
if (slot.includes('item')) { // real criteria taken out for stackflow
do {
const randomNumber = Math.floor(Math.random() * (listTemp.length - 1) + 1);
let randomItem = listTemp[randomNumber];
if (1 == 1) { // real criteria taken out for stackflow
let chance = Math.round(Math.random());
if (chance) {
randomItem.Name += '(altered)';
}
}
results.splice(index, 1, randomItem);
} while (1 != 1); // real criteria taken out for stackflow
};
};
});
I expect it to write the altered "randomItem.Name" only to randomItem itself. Not even to listTemp but definitly not to the global "list". Do you have any idea why it is doing this and how i can prevent this? How can i get the object into randomItem without randomItem keeping its reference to any list. Thank you guys in advance!
I need to find out the difference in the old and new value of the localStorage when the change event if triggered.
I can toggle the same localStorage key within different tabs, so if I add one the values would be:
'1234,4321'
But then when I remove one it would be:
'1234'
My code below will convert the string to an array, separating the comma. However this only seems to work on way around, so if I remove one the code below will display an empty array, instead of the removed number.
window.addEventListener('storage', function (e) {
if (e.key === 'favourites') {
let newv = e.newValue.split(',').filter(id => !!id);
let oldv = e.oldValue.split(',').filter(id => !!id);
let difference = newv.filter(function (i) {
return oldv.indexOf(i) === -1;
});
console.log(difference);
}
});
What is the best way to do this!?
So you need to check for added by looking to see if the original does not have it from the new values. And to check for a removed item, you need to check that the id does not exist in the orginal values.
const oldValue = '1234,4321'
const newValue = '1234,5555'
const oldValueIds = oldValue.split(",")
const newValueIds = newValue.split(",")
const removed = oldValueIds.filter(id => !newValueIds.includes(id))
const added = newValueIds.filter(id => !oldValueIds.includes(id))
console.log('removed: ', removed)
console.log('added: ', added)
I need help doing the following.
I need to duplicate an array, update a value and insert it into a new object.
My Code right now:
// Sample test values {name:'The initial value', altName:'a first Name;a second name'}
var allAltName = test.altName;//Test come from a forEach() Iteration
if (test.altName) {//First I check if ther is my parama altName
var b,
countAllAltName = allAltName.split(';'); //Here I split my parameter string based on ';'
if (countAllAltName.length > 0) {
for (b = 0; b < countAllAltName.length; b = b + 1) {
var originalName = {};//I create a new object
originalName = test;//I load my existing object into a blank object
if (!ret["Index"]) // I check if my final object Key exist
ret["Index"] = {}; // if not create new object
if (!ret["Index"]["Index"]) // check another key
ret["Index"]["Index"] = []; // if not create new
originalName.name = countAllAltName[b];//Update my new object originalName with new value
ret["Index"]["Index"].push(originalName); // push current element in the designated list
ret["Index"]["Index"].sort(function (a, b) {
return a.name.localeCompare(b.name);
});
console.log(ret);
}
}
}
Issue is ret contains the required Object keys,but all value of name in each aray have the same last value of altName
I console.log() at each step what is the value of originalNameit always looks good.
Why the end results failed, and where I'm overwriting my data.
When you write originalName = test, you tell to JS that originalName is an "alias" for test (both share the same reference).
The behaviour is what you change in originaleName, it's impacted in test and vice versa (behaviour true only for Array and Object).
If you want to do a real copy, the simplest way (but with restrictions) is :
originalName = JSON.parse(JSON.stringify(test));
Last things : var originalName = {} is not an Array but an Object. There are some important differences between them
I hava a problem with copy a objects to array. I think it is an problem with reference.
In my program i have few array. First is dataForMonth - it is array of objects with data for month. And second is an products array which contains products objects. Product have property forecastArry wchich is array of objects.
Here code :
this.allProducts.map(function (product) {
var dataForMonth = data.filter(function (e) {
return e.dataId === product.productDataId;
});
var z = { posId: product.sales_plan_pos_id, arry: [] }
for (var sheetMonth of sheet.channels) {
var result = dataForMonth.filter(function (e) {
return e.CHANNEL === sheetMonth.CHANNEL;
});
product.forecastArry[someId].channels = result;
);
The problem is that the every changed channels property have the same value - its a value from last product?
Anybody know how to fix it ?
Seems like you want to edit each product in this.allProducts. So you want to add a return value to your map. You should also use let so that the scope of variables declared is preserved within map function, although I believe the map function already takes care of that. In addition, not that you have to reassign this.allProducts to your map function call. So your answer should be something like the following:
this.allProducts = this.allProducts.map(function (product) {
let dataForMonth = data.filter(function (e) {
return e.dataId === product.productDataId;
});
let channelsForMont = [];
let z = { posId: product.sales_plan_pos_id, arry: [] }
for (let sheetMonth of sheet.channels) {
let result = dataForMonth.filter(function (e) {
return e.CHANNEL === sheetMonth.CHANNEL;
});
product.forecastArry[someId].channels = channelsForMont;
return product;
);
P.S Your original code has some missing brackets and result variable is unused. You should do something about them.
I have an svg map with several points where I want to store the initial position of each point in an array. And each point has it's own ID, like point_1, point_2 etc.
I have attached a click handler to each of these and run a function when they are clicked.
So what I want to do in this function is to check if the array already contains the information of the clicked element. If it doesn't, I want to create it.
This is what I want to do, in pseudo code
var arrPoints = [];
zoomToPoint('point_1');
function zoomToPoint(data_id) {
// Does array already contain the data?
if (!arrPoints.data_id) {
// Add data to the array
arrPoints.data_id.clientX = somevalue;
arrPoints.data_id.clientY = somevalue;
}
}
This would basically create an array that looks like this:
arrPoints.point_1[]
arrPoints.point_2[]
Where I can access the data in each .point_1 and .point_2.
But I can't create an array based on a variable, like this:
arrPoints.data_id = [];
Because I end up with data_id as the actual name, not the variable that data_id actually is. So how is this usually accomplished? How can I identify each point to the actual array?
Sorry for my lack of basics
Just use an object:
var arrPoints = {};
zoomToPoint('point_1');
function zoomToPoint(data_id) {
// Does array already contain the data?
if (!arrPoints[data_id]) { // square brackets to use `data_id` as index
// Add data to the array
arrPoints[data_id] = {};
arrPoints[data_id].clientX = somevalue;
arrPoints[data_id].clientY = somevalue;
}
}