JavaScript array of array of objects [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Currently I am having a problem with JavaScript arrays where if I update a value in an array it updates the value in both arrays.
My current array looks like this
billarr[camp][e].dataa = t;
For example if you try update the array like
billarr[22][1].dataa = "blabla";
It updates the dataa value in both
billarr[22]
and
billarr[23]
to the dataa var being "blabla"
I have spent hours looking what is the possible solution and am desperate if anyone has any advice
array population code
message ={};
temparr4 =[];
message.typee= $("#type"+data[i].id).val();
message.events= $("#event"+data[i].id).val();
message.network=data[i].network;
message.network_des=data[i].network_des;
message.dataa=data[i].data;
temparr4[data[i].id]=message;
and then loop(sets default array content)
camparr.forEach(function(i,e) {
billarr[e] = temparr4;
});
without using objects still has same array update issue.
message =[];
temparr4 =[];
message[0]= $("#type"+data[i].id).val();
message[1]= $("#event"+data[i].id).val();
message[2]=data[i].network;
message[3]=data[i].network_des;
message[4]=data[i].data;
temparr4[data[i].id]=message;
and then loop(sets default array content)
camparr.forEach(function(i,e) {
billarr[e] = temparr4;
});
This still updates both arrays billarr[22] and billarr[23]
billarr[camp][e][4] = t;
I have updates with code using no objects and just arrays but the array does the same as object and updates both arrays at specific element

You're constructing your array incorrectly, and storing the same object in two places in the array, rather than storing two separate objects.
You haven't shown nearly enough of your code for us to help you with it, but here's an example:
// An array
var a = [];
// An object
var o = {data: "foo"};
// Putting that object in the array
a.push(o);
// Putting it in again -- this results in the *same* object being in the array twice
a.push(o);
// If we change object...
a[0].data = "bar";
// ...it's the *object* that gets changed, so it doesn't matter which
// reference we use when looking at it:
console.log(a[0].data); // "bar"
console.log(a[1].data); // "bar"
console.log(o.data); // "bar"
The solution is to create a new object after pushing the old one onto the array
// An array
var a = [];
// An object
var o = {data: "foo"};
// Putting that object in the array
a.push(o);
// Creating a *new* object
o = {data: "testing"};
// Pushing the new object in the array
a.push(o);
// If we change object...
a[0].data = "bar";
// ...the other object isn't changed:
console.log(a[0].data); // "bar"
console.log(a[1].data); // "testing"

Related

How to get the first value in JSON brackets [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a function that returns the following:
{ 'random_string': '' }
Where random_string is an id that I do not know until it is returned.
How do I extract the value of random_string in JS? Thank you.
var a = { 'random_string': '' }
console.log(Object.keys(a)[0])
Your variable a has a value of type Object. Take a look at the Object prototype's documentation and see which methods are available to you: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
You're trying to get your object's first key, and so conveniently you can use Object.keys as follows:
var a = { 'random_string': '' }
// Get array of Object's key values as strings
var aKeys = Object.keys(a);
console.log(aKeys);
// Print first key, in this case you only have one
console.log(aKeys[0]);
But based on your comments, you're going about this wrong.
If your "random_string" property identifier is truly random, you'd want to store the random string as an object property value.
That might look something like this:
// Generate some random string value
var random = Math.random().toString(36).substring(7);
// Create an object with a predefined object property identifier
var data = { 'random_value': random };
// Access the random value using your known property identifier
console.log(data.random_value);

Why do only some array methods create new instances? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am new to javascript. Coming from a more object oriented background, one quirk I noticed is that some methods override an array, and some others make new instances. For example:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the original array
arr.push("Hola");
console.log(arr);
whereas concat
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([ // original array needs to be overridden
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Why is the behavior between the two methods not consistent?
Examples taken from: How to append something to an array?
var foo = 1, bar = 2;
Let's say you wanted to add the values foo and 1 onto bar. This is what you would do:
var foo = 1, bar = 2;
bar = bar + foo + 1;
console.log(bar) //4
But you did not do this:
var foo = 1, bar = 2;
bar + foo + 1; //ineffective
console.log(bar) //2
That is because the operator + simply just adds the values and returns the sum. So you still need to redefine bar. Whereas in:
var foo = 1, bar = 2,i;
for(i=0;i<foo;i++) bar++; //adds 1 foo times
bar++; //adds 1
You do not need to make a redefinition. This is because the increment operator assumes that you want to increment a value, not find their sum. So it does that.
array.concat(foobar) assumes that you want to get two arrays or values, join them together into a new, combined array, and then return the new array. In a sense, it is like the + operator. Thus it only finds their combination, not set the actual array, so you need a redefinition.
Whereas array.push(foobar) assumes that you want to add, stick, glue, or push a value to the end of the array, so it will do so. And because it itself has already added those onto the array, it doesn't need to be used in a redefinition.
They are used in that sense. It may be inconsistent, but you need to become used to it.
concat() method does not change the existing array, but returns a new reference.

How to create a new object from my existent object in Javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
How do I create a new object from my other object please? So I have this code:
var test = {
p1: [
'factorial',
'11'
],
p3: 'temp1',
x1: 'factorial'
};
and I want to get this:
Newobj = {
factorial: [
'p1',
'x1'
],
11: 'p1',
temp1: 'p3'
}
To explain more: the values from the first object will be the keys in the second, but as you see there is an array, I need to go through all the values. Plus, I don't want to get a repeated one. For example, factorial exists in two keys : p1 and x1 so factorial needs to be written only once but with an array containing from where we got it.
Thank you!!
I'm just a sucker for these map/reduce problems.
I would first create a map of test value to an array of test keys matching that value.
Then reduce that map to a plain object, taking the array value if its length is greater than one, otherwise just the first entry.
const test = {"p1":["factorial","11"],"p3":"temp1","x1":"factorial"}
// create an intermediary Map of keys and values
const newMap = Object.keys(test).reduce((map, key) => {
// force the value to an array for consistency and iterate
[].concat(test[key]).forEach(val => {
// create or add to the "key" to the array at map.get(val)
map.set(val, (map.get(val) || []).concat(key))
})
return map
}, new Map())
// now reduce the Map entries to a plain object
const newObj = Array.from(newMap).reduce((obj, [key, val]) => ({
...obj,
[key]: val.length > 1 ? val : val[0] // only use an array if more than one entry
}), Object.create(null)) // Object.create(null) creates a plain object
console.info(newObj)
Some advice though... I would make all the values arrays, even if there's only one entry. This create a consistent API for iterating and consuming your object.

javascript arrays difference [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
am confused what this code deos so can anyone explian it to me the reason behind it.
function diff(arr1, arr2) {
var newArr = [];
var h1 = Object.create(null);
arr1.forEach(function(e) {
h1[e] = e;
});
var h2 = Object.create(null);
arr2.forEach(function(e) {
h2[e] = e;
});
Object.keys(h1).forEach(function(e) {
if (!(e in h2)) newArr.push(h1[e]);
});
Object.keys(h2).forEach(function(e) {
if (!(e in h1)) newArr.push(h2[e]);
});
return newArr;
}
i found it when i was searching how to get the difference between javascript arrays
breif explanation will be help full
Comparing 2 Arrays and finding all the differences is slow. The reason is because the lookup time is not fast.
Say you have the following:
var arr1 = [1,2,3,4];
var arr2 = [5,6,7,8];
What you want is to find every value in arr1 that isn't in arr2, AND every value in arr2 that isn't in arr1. To do this, you loop over arr1 and ask "is this value in arr2?" But each time you ask that, you have to also loop over arr2. Then, you have to repeat this again with arr2, looking up each value in arr1.
This Javascript method speeds things up. In Javascript, Objects are created as a set of unique keys and their corresponding values. For instance:
var obj1 = {a: "string a", 6: "number 6"};
Now, I can say obj1['a'] and it will return "string a". Not only can the keys and values be any time (number, string, Object), but the lookup is instantaneous. We no longer have to look at every key in obj1, so if we can take advantage of this, our logic would be much faster.
The first thing this Javascript method does is convert both Arrays into Objects. It uses the Array values as both the Object key and value, and we end up with h1 and h2.
Then, it does the logic I mentioned above. It looks at every key in h1 (this optimization eliminated duplicate Array values, because the Object key must be unique), and if that key is not in h2, it adds the value to newArr. Then this repeats for all keys in h2.
Basically, it optimizes our search by reorganizing our slow Array values into fast key-value Objects, then does the necessary comparisons.

Object Obect array Json.stringify string array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I had a object object array which i used JSON.stringify() on i can now see what's in my array but when i do arr[0] etc it only outputs one letter.
arr = {"hello":"yes","because":"no"}
arr[0] =h
I want it to output the whole of the value not just the first letter
My code
var clientContext = SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
// Get user properties for the target user.
// To get the PersonProperties object for the current user, use the
// getMyProperties method.
MyProperties = peopleManager.getMyProperties();
// Load the PersonProperties object and send the request.
clientContext.load(MyProperties);
clientContext.executeQueryAsync(getMyNewsChoicesSuccess, getMyNewsChoicesFail);
},
getMyNewsChoicesSuccess = function () {
//get the news choice by actually fieldname
var MyChoices = JSON.stringify(MyProperties.get_userProfileProperties().Value);
$('#NBStest').text(MyChoices);
},
You can get the first element from your json string like this
JSON.parse(json_str)[0]
but in the example you have, the first element is "yes" and its index is "hello" , which means you can't get the first element by the index 0 , however you can get it by its property name like this
arr.hello = "yes";
// or
arr['hello'] = "yes";
if you want to get the hello which is the key , you have to use this loop
for (key in arr)
console.log(key);
// it will print 'hello' and then 'because'
Well its not an array anymore, its a string. arr[0] will return the first letter.
If you want to get the objects from it you need to parse it ( try JSON.parse )
JSON.stringify() does exactly what it sounds like. It turns the javascript object into a string. So when you do arr[0] you are getting the first letter in the string. You need to turn it back into a javascript object if you want to get the actual values.

Categories

Resources