var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
arr now looks like this -> [key, Array(1)]
New data comes into barr how to i push another item into the nested array for the same key?
expected output should be something like this: [key, Array(2)]
Option #1:
You can push into the barr array:
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
console.log(arr);
barr.push('key2', 'key3');
console.log(arr);
barr is a reference to the array, and when you pushed it into your arra array you actually put there the reference, so when updating barr your reference is still there (and updated).
Option #2:
You can push into the array that is in the 2nd place of your array:
var arr = []; //is a multidimensional array.
var barr = []; //is a temp array that is dynamically updated
var key = "key1"
arr.push(key, barr);
console.log(arr);
arr[1].push('key2', 'key3');
console.log(arr);
The way you did it the "key" is actually just another value in the array (at index 0). If you want to use a string as the key you'll have to use an object. You can set and get properties using the bracket syntax. The bracket syntax works with arrays as well, but only using integers as keys.
var obj = {};
var barr = [];
var key = "key1";
obj[key] = barr;
// barr changed
obj[key] = barr;
Related
I have this data structure. I have used the underscorejs but could not find way to that like the below structure
var data = [{"5+":2},{"3-5":0},{"1-3":1},{"0.5":0},{"<30":0},{"5+":1},{"3-5":1},{"1-3":0},{"0.5":0},{"<30":0},{"5+":3},{"3-5":0},{"1-3":3},{"0.5":0},{"<30":0}];
var groupArr = [];
##loop through the data##
data.forEach(function(item){
##find the keys ##
var keys = Object.keys(item);
var obj = {};
obj[keys] = [];
##push the data to object keys array##
obj[keys].push(item[keys])
groupArr.push(obj)
})
By using this data structure I want something like this structure
[{"5+":[2,1,3]},{"3-5":[0,1,0]},{"1-3":[1,0,,3]},{"0.5":[0,0,0]},{"<30":[0,0,0]}]
As I have tried everything but could not find the solution any help would be highly appreciated.
The first part converts the list of objects to a single object, where the keys are each of the unique keys from the list of objects and the values for each key are joined as an array:
{
"5+": [2,1,3],
"3-5": [0,1,0]
...
}
Since this is not the format you wanted, the second part converts this object into a list of objects by looping over each key and creating a new object from it.
var data = [{"5+":2},{"3-5":0},{"1-3":1},{"0.5":0},{"<30":0},{"5+":1},{"3-5":1},{"1-3":0},{"0.5":0},{"<30":0},{"5+":3},{"3-5":0},{"1-3":3},{"0.5":0},{"<30":0}];
// create object with all the values joined together in lists.
var map = data
.reduce(function (map, obj) {
var key = Object.keys(obj)[0];
// checks if the key allready exits in the new object.
// If it does we push a new value into the array,
// otherwise we create a new property with a list with one value.
map[key] ?
map[key].push(obj[key]):
map[key] = [obj[key]];
return map;
}, {});
// convert above result to a list with objects.
var newFormat = Object.keys(map)
.map(function (key) {
var obj = {};
obj[key] = map[key];
return obj;
})
console.log(newFormat)
Two problems consider the following object:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
Why does my cars array have length of 0? Do i have to update the length property manually?
Why is my stringified object empty when it has parameters in it i'm assuming it is tied into the length property?
Fiddle:https://jsfiddle.net/wcd7f8Lz/
car is initialized as an array, but used as an Object. and an object does not have length attribute...
To get the length of an object, you can do ̀̀̀̀Object.keys(obj).length (get the keys list, and because it is an array, it have a length).
But the problem is also that you initialize cars as an array, but use it as Object...
see docs here:
http://www.w3schools.com/js/js_arrays.asp
http://www.w3schools.com/js/js_objects.asp
The solution is to initialize it as Object:
//new obj
var obj = {};
obj['cars'] = {}; //And other object
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
But if you want instead a simple array:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars'][1] = "toyota";
obj['cars'][0] = "mazda";
console.log(obj);
console.log(JSON.stringify(obj));
The syntax is ̀array[identifier] = value;
(and not ̀̀̀̀̀array[value] = identifier)
I've updated the fiddle.
obj.cars.length is 0, because you don't push new items in array, but change it properties:
var obj = {};
obj.cars = []; // obj.cars is empty array
obj.cars.toyota = 1; // obj.cars is empty array with a new property toyota
obj.cars.push('mazda'); // obj.cars is array with a new property toyota and one element mazda
console.log(obj.cars instanceof Array,
obj.cars.length,
Object.keys(obj.cars)); // output: true 1 ["toyota"]
Why you don't use it in this way?
var cars = [];
cars.push({name:'toyota', value:1});
cars.push({name:'mazda', value:0})
That's because you aren't using an array (despite declaring it with an array literal), you're using it as an object.
Arrays are just a special case of object, meaning they can have individual properties. These properties don't exist "in" the array but instead are properties "of" the array.
var arr = [1, 2, 3];
arr.thing = 'a';
console.log(arr.length); // 3
To add elements to an array, you should use push:
var arr = []; // length: 0
arr.push(1); // length: 1
If you want to be able to access an object both by name and index then you can combine push with custom properties.
var arr = [];
arr.push(0);
arr.mazda = 0;
I'm trying to push some datas into my array.
Actually my code looks like this:
arr.push('step1||item1||99');
It works but it's not the best as I need to split it after to manager datas.
How can I transform this into a multidimensional array ?
What I tried:
arr = [];
arr['step'] = 'step1';
arr['name'] = 'item1';
arr['number'] = '99';
arr.push(arr);
But it doesn't work...
Any help please.
Is there a reason you don't want these individual data points to be objects?
var arr = [];
var dataPoint = { 'step': 'step1', 'name': 'item1', 'number': 99 };
arr.push(dataPoint);
If this isn't what you're looking for, can you give a fuller explanation of what your dataset should look like so we can better understand the problem?
Array holds "indexes"
Object holds "Key" and "Value"
Array example:
var arr = new Array;
arr[0] = 'step1';
arr[1] = 'item1';
arr[2] = '99';
console.log(arr);
Object example:
var obj = new Object;
obj.stop = 'step1';
obj.item = 'item1';
obj.number = 99;
console.log(obj);
Objects in array:
var arr = new Array;
var obj = new Object;
obj.stop = 'step1';
obj.number = 99;
arr.push(obj)
console.log(arr); // Output => [{stop: 'step1', number: 99}]
maybe you mean something like this
arr=[];
var s={
step:'step1',
name:'item1',
number:'99'
}
arr.push(s);
console.log(arr);
s is an object, which works just like an array, but is referenced by a string instead of an integer:
s['step'] === 'step1'
s.step === 'step1'
arr[0] === s
Be aware that there are some differences, like you can't iterate over an object like you can an array: you need to use another method like a "for in" loop, for instance.
I have an array of objects as
var obj = {'name': 'John'};
var obj2 = {'name': 'Sam'};
var arr = [];
arr.push(obj);
arr.push(obj2);
Now I create a new array arr2 as
arr2 = arr.slice();
Now if I change arr2[0]['name'] = 'David';
then arr1[0]['name'] also becomes 'David';
How can we prevent any object value of arr from changing when arr2 object values are changed.
You’ll have to clone each object, not just the array:
function cloneObject(obj) {
var result = {};
for (var k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
result[k] = obj[k];
}
}
return result;
}
var arr2 = arr.map(cloneObject);
Is there a way we can prevent the objects from changing?
Yes, there’s Object.freeze:
arr.forEach(Object.freeze);
When you copy the array you are only copying the values in the array, but the values are references to objects. You end up with two separate arrays, but with references to the same objects.
You would need to make a deep copy, i.e. copy everything at every level:
var arr2 = JSON.parse(JSON.stringify(arr));
Now you have a completely separate copy of the array and everything in it.
Sorry for my last question being so confusing, I was confused my self, but now I got a proper example:
var obj = {};
obj.entities = [];
obj.entities["player"] = [];
obj.entities["player"]["0"] = [];
obj.entities["player"]["0"]["pos"] = "0,0";
var jsonStr = JSON.stringify(jsonObj);
// {"entities":[]}
console.log(JSON.stringify(obj));
The output of JSON.stringify(obj) is wrong as you can see.
What causes this ?
You're first building an array ([]), then assigning properties to it with non-number keys (player). This is technically possible (as in not causing an error), but it's not what arrays are for.
You should use objects ({}) instead. Also, ["player"] is the same as .player.
var obj = {};
obj.entities = {};
obj.entities.player = []; // array here because you're filling with indices ([0])
obj.entities.player[0] = {}; // object again, because non-indices as keys (`pos`)
obj.entities.player[0].pos = "0,0";
Objects can take any property key. Arrays are a subset of objects, which should only have indices (numbers >= 0) as keys.
Your life would be much easier if you'd define your objects in JSON to begin with:
var obj = {
'entities': [
{'player':{'pos': '0,0'}}
]
};
You're using named array indeces instead of object key/value pairs.
var obj = {};
obj.entities = {};
obj.entities["player"] = {};
obj.entities["player"]["0"] = [];
obj.entities["player"]["pos"] = "0,0";
// {"entities":{"player":{"0":[],"pos":"0,0"}}}
console.log(JSON.stringify(obj));
entities, and entities["player"] and entities["player"]["0"] need to be objects, not arrays.
You're adding properties to these arrays, rather than pushing values onto them. These custom properties are not getting stringified.
The fix is simple:
var obj = {};
obj.entities = {}; // <------------ this is an object now
obj.entities["player"] = {}; // <--------- also an object
obj.entities["player"]["0"] = {}; // <-------- and so on
obj.entities["player"]["0"]["pos"] = "0,0";
I think you have some serious confusions about arrays and objects in javascript. An array ([]) works only with positive integer indexes. In your example you are doing the following:
obj.entities = [];
obj.entities["player"] = [];
You say that obj.entities is an array and then you use player as index. And player is not an integer. So this code makes no sense. On the other hand you could use objects with properties. Those properties can be strings:
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = 'foo bar';
You are confusing objects with arrays. The following code will work.
var obj = {};
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = {};
obj.entities.player[0].pos = "0,0";
The things you went wrong:
An array can have only integer indexes. So it's incorrect writing a["1"] if you intend to use a as an array.
To be correctly serialized, only an object can have named properties, like object.entities.player or object.entities["player"].