Deleting element from a long object - javascript

I have an object that looks like this:
[{"1":{"name":"A","email":2}},
{"2":{"name":"B","email":3}},
{"3":{"name":"C","email":4}},]
{"4":{"name":"B","email":5}}]
I want to have a result like below:
[{"name":"A","email":2}},
{"name":"B","email":3}},
{"name":"C","email":4}},]
{"name":"B","email":5}}]
I tried but this code is not working, now I am a bit lost as to how to approach a solution for this.
obj.map(a => {
var newobj
a = []
a.push[a]
})

you need to read about Array.prototype.map() and the way you use it is not the proper way
var homework =[{"1":{"name":"A","email":2}},
{"2":{"name":"B","email":3}},
{"3":{"name":"C","email":4}},
{"4":{"name":"B","email":5}}];
var outputofthehomework = homework.map( s => Object.values(s)[0] );
console.log(outputofthehomework)

var a = [{"1":{"name":"A","email":2}},{"2":{"name":"B","email":3}}, {"3":{"name":"C","email":4}}, {"4":{"name":"B","email":5}}];
var b = [];
a.forEach(function(element){
for (var key in element){
b.push(element[key]);
}
});
console.log(b)

Related

Javascript Appending to 2-D Array

I am trying to append an array to an array. I am expecting the output to be something like:
[[Dep,POR],[14073,99.25],[14072,0.06]]
But I am getting:
Dep,POR,14073,99.25,14072,0.06
Here's what I have so far:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = ['Dep','POR'];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_por = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(hist_por);
}
When you initialize hist_por, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:
hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]
Also per #justrusty's answer, you need to JSON.stringify(hist_por) when you pass it to document.write(). This is the more important piece so his answer should be accepted.
So the whole code block would become:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = [['Dep','POR']];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_rop = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(JSON.stringify(hist_por));
}
This may help you https://codepen.io/anon/pen/xQLzXx
var arr = ['foo','bar'];
var arr2 = ['baz', 'boo']
arr.push(arr2);
console.log(arr);
document.write(arr);
document.write("<br>");
document.write(JSON.stringify(arr));
It's basically just the way it writes it to document. If you log it in console you'll see the array appended. Or if you JSON.stringify() first it will show as you expect.
My advice is ALWAYS console.log() so you can see exactly how the data is structured
The others have already pointed out what the problem is (+ there's a typo in one of your variable names - arr_rop vs arr_por). Here's an ES6 version that will break in older browsers, for learning purposes:
function get_historical() {
const well = document.getElementById('wellSelect');
const selected_well = well.options[well.selectedIndex].value;
const hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
const hist_por = Object.values(hist_json_obj).reduce(
(arr, item) => [...arr, [item.dep, +item.por]],
[["Dep", "POR"]]
);
document.write(JSON.stringify(hist_por));
}

JavaScript Split from comma separated to array list with values

What I'm trying to do is from a comma separated text (like this one):
hello,test,ciao
Get a javascript array with a predetermined value.
I know how to split a comma-separated list, but I don't know how to add a value inside them.
Actual code:
HTML
<input onkeyup="test()" type="text" id="origin">
<div id="response">
</div>
JAVASCRIPT:
function getValue(){
var returnV = $("#origin").val();
return returnV
}
function test(){
var origin = getValue();
var array = origin.split(',');
console.log(array)
}
OUTPUT
["hello", "test", "ciao"]
WHAT I'M TRYING TO GET
{
"hello":"predetermined value",
"test":"predetermined value",
"ciao":"predetermined value",
}
I think this question is interesting because this way yo can, for example, create new configurations with a starter value and add custom confirgurations for each of them later. I know that the split part is already replied on stackoverflow, what I'm having trouble with is with adding the default values :), thank you very much in advance.
didn't want to change your code so much. just have a look up to object creation.
function getValue(){
return document.getElementById("origin").value
}
function test(){
var obj = {}
var origin = getValue();
origin.split(", ").forEach(function(e) {
obj[e] = "predeterminated value";}
);
console.log(obj);
}
<input onkeyup="test()" type="text" id="origin">
<div id="response">
</div>
Have you tried iterating over the array? Like this:
function getValue(){
var returnV = $("#origin").val();
return returnV
}
function test(){
var origin = getValue();
var object = {}
var array = origin.split(',');
array.forEach((item) => {
object[item] = "predeterminated value"
}
console.log(object)
}
A couple notes: try to give more meaningful names to your variables; the word is "predetermined",
Store your output to a variable:
var output=["hello", "test", "ciao"]
Then do something like this with it:
var newObject={};
for(var i in output){
var property=output[i];
newObject[property]='predeterminated value';
}
Example JSFiddle (open console to see result)
Split your string and then use Array.prototype.reduce to build an object from it.
var original = "hello,test,ciao";
var obj = original.split(',').reduce(function(p,c) {
p[c] = "predeterminated value";
return p;
}, {});
console.log(obj);
It's not exactly clear where predeterminated value is supposed to come from. If it's the same for all properties of your object, then this will work as-is. If it's not, you'll have to figure out how to select the right value.
Hey you can follow the below code snippet this will help
function getValue(){
var returnV = 'hey,your,input,keys,goes,here';
return returnV;
}
function test(){
var origin = getValue();
var array = origin.split(',');
var finalObj = {};
var defaultVal = 'pre-def';
for(var i=0;i<array.length;i++){
finalObj[array[i]] = defaultVal;
}
console.log("arry",array)
console.log("converted",finalObj)
}
test();

How to put data into multi dimensional array in js inside the loop

How can we put data into multi dimensional array or json within a loop.
I know that it's possible to store multi dimensional data at one time, but I want it inside the loop as I have described in the code.
var sub_cat_checked_val = [];
sub_cat_checked.each(function (index) {
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
sub_cat_checked_val['key_one']['key_two']='value';
sub_cat_checked_val[sub_cat_id][index] = index:jQuery(this).val();
});
As it's possible in php like $var_name['key1']['key2']['keyn']='value';
sub_cat_checked_val[sub_cat_id] needs to be defined as an array, so add the lines:
if (!sub_cat_checked_val[sub_cat_id]) {
sub_cat_checked_val[sub_cat_id] = [];
}
to define the value as an array if it does not exist.
Try this snippet:
<script>
var k = {};
k.a = {};
k.a.b = {};
k.a.b.c = {};
k.a.b.c.d = 5;
console.log(k);
</script>
I was able to do it with all of you guys help with some of modifications.
Here is what I did:
sub_cat_checked.each(function (index) {
console.log(index_val);
var sub_cat_id = jQuery(this).attr('name').replace('subcategory_id_', '').replace('[]', '');
console.log(sub_cat_id);
if (sub_cat_checked_val[sub_cat_id] == undefined) {
sub_cat_checked_val[sub_cat_id] = [];
}
sub_cat_checked_val[sub_cat_id][index] = jQuery(this).val();
});
Thanks a lot to all of you.

Javascript: forEach() loop to populate an array - closure issue

Let's say we have an array of objects like:
var fruits = [ {name:"banana", weight:150},{name:"apple", weight:95},{name:"orange", weight:160},{name:"kiwi", weight:80} ];
I want to populate a "heavy_fruits" array with items from the "fruits" array above which weight is > 100. Here is my code:
var heavy_fruits = [];
myfruit = {};
fruits.forEach(function(item,index) {
if ( item.weight > 100 ) {
myfruit ["name"] = item.name;
myfruit ["weight"] = item.weight;
}
heavy_fruits.push(myfruit);
});
However it shows:
name:"orange", weight:160
name:"orange", weight:160
name:"orange", weight:160
name:"orange", weight:160
I know this is an issue with mixing closures and loops... but I read an article (http://zsoltfabok.com/blog/2012/08/javascript-foreach/) explaining that I would avoid this kind of issue using a forEach loop instead of the classic for loop.
I know I can use array methods like filter(), etc. but I'm asking that on purpose since I'm actually having troubles with a much bigger function that I cannot expose here... So I tried to summarize and simplify my issue description with "fruits".
var heavy_fruits = [];
myfruit = {}; // here's your object
fruits.forEach(function(item,index) {
if ( item.weight > 100 ) {
myfruit ["name"] = item.name;
myfruit ["weight"] = item.weight; // you modify it's properties
}
heavy_fruits.push(myfruit); // you push it to the array
});
You end up with an array [myfruit, myfruit, myfruit, myfruit].
Now if you modify myfruit anywhere in the code, the change will be visible in every single occurence of myfruit. Why?
Because you are modifying the referenece to the object.
In this example, your array stores just copies of your object. And if you change one of it, every single one will change, because they are all references.
To fix this with each iteration you should be creating a new object and then doing some stuff on it.
BTW, as a matter of fact, your if could just be like this:
if ( item.weight > 100 ) {
heavy_fruits.push(item); // if `item` only has `name` and `weight` properties
}
fruits.forEach(function (item, index) {
if (item.weight > 100) {
myfruit = {};
myfruit["name"] = item.name;
myfruit["weight"] = item.weight;
heavy_fruits.push(myfruit);
}
});
The shorter would use filter
var heavy_fruits = fruits.filter(x => x.weight > 100);
But if you realy want to use forEach do this way
var heavy_fruits = [];
fruits.forEach(x => {if(x.weight > 100) heavy_fruits.push(x)} );

creating nested array javascript

Have looked at many examples but cant seem to get to make an nested array to store some data nicely. How can I get the following code to work? It gives me an error now:
var shipdata = [];
shipdata['header']['bedrijfsnaam'] = $('[name="bedrijfsnaam"]').val();
shipdata['header']['naam'] = $('[name="naam"]').val();
shipdata['header']['straat'] = $('[name="straat"]').val();
shipdata['header']['postcode'] = $('[name="postcode"]').val();
shipdata['header']['plaats'] = $('[name="plaats"]').val();
shipdata['header']['telefoon'] = $('[name="telefoon"]').val();
shipdata['header']['email'] = $('[name="email"]').val();
shipdata['header']['instructies'] = $('[name="instructies"]').val();
shipdata['header']['ordernummertje'] = $('[name="ordernummertje"]').val();
$(".pakketten").each(function(index, element) {
index++;
shipdata['pakketten']['pakket'+index]['lengte'] = $('[name="lengte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['breedte'] = $('[name="breedte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['hoogte'] = $('[name="hoogte'+index+'"]').val(),
shipdata['pakketten']['pakket'+index]['gewicht'] $('[name="gewicht'+index+'"]').val()
});
Probably im doing this all wrong, but some pointers would be welcome.
Thanks!
First of all, you are creating an object and not an array, so use {} instead of [] for the main container.
Second, when inserting multiple values at the same time, you can use a much more compact notation:
var shipdata = {
'header': {
'bedrijfsnaam': $('[name="bedrijfsnaam"]').val(),
'naam': $('[name="naam"]').val()
'...': '...'
},
'pakketten': []
};
$(".pakketten").each(function(index, element) {
shipdata['pakketten'].push({
'lengte': $('[name="lengte'+index+'"]').val(),
'breedte': $('[name="breedte'+index+'"]').val(),
'...': '...'
});
});
Besides, anytime you want to access an object or array in any way, you have to initialize it beforehand as already mentioned by #antyrat.
You need to create objects each time you want to have nested array:
var shipdata = {};
shipdata['header'] = {};
shipdata['header']['bedrijfsnaam'] = $('[name="bedrijfsnaam"]').val();
//...
shipdata['pakketten'] = {};
$(".pakketten").each(function(index, element) {
index++;
shipdata['pakketten']['pakket'+index] = {};
shipdata['pakketten']['pakket'+index]['lengte'] = $('[name="lengte'+index+'"]').val(),
// ...
Answer updated due to comments as arrays didn't have string indexes.

Categories

Resources