jquery creating two dimensional array - javascript

Edit: It appears I was a bit confused on what I was trying to accomplish. For those that took the time to explain this, thank you.
I'm trying to create a two dimensional array in Jquery/Javascript. I've done a decent amount of searching, testing and more searching but i'm unable to find a solution that really makes sense to me. (it's been a very long week already....)
Below is the desired format of the array.
{"product":[{"attribute":"value","attribute":"value"}]}

That's not a 2D array, but rather an object. Also, your product array contains only one object. I think you need something like this:
var obj = {};
obj.product = [];
for(var i=0; i < someObj.length; i++) {
obj.product.push[{"attribute": someObj[i]}]
}
This will produce an array inside the product property:
{"product":[{"attribute":"value"}, {"attribute":"value"}]}

You can't create a two dimensional array in Javascript, arrays can only have one dimension. Jagged arrays, i.e. arrays of arrays, are used instead of two dimensional arrays.
Example:
var a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
The desired format that you show is neither a two dimensional array nor a jagged array, instead it's an object containing a property that is an array of objects. However, the object in the array has two properties with the same name, so I assume, you meant that as having two objects in the array:
var o = {
product: [
{ attribute: "value" },
{ attribute: "value" }
]
};
You can create an object like that using a literal object like above, or you can create it by adding properties and array items afterwards:
var o = {};
o.product = [];
o.product.push({ attribute: "value" });
o.product.push({ attribute: "value" });

Try this:
{"product":[ [{"attribute":"value"},{"attribute":"value"}]]}

$(".adddiv").each(function(){
tasks = [];
$(".subtasktask"+len).each(function() {
var raw = $(".subtasktask"+len).children().size();
for(var l =0;l
datas.push(milestone);
alert("now show json milestone array : ");
alert(milestone.month + ":" + milestone.title +":" + milestone.task. );
len++
});

This is my solution.
var optionArr = []
optionArr = {"product": [{"id":1, "name":"abc"}, {"name":"value"}]}
var data = optionArr['product'][0]['name']
alert(data)

Related

How to check if array contains objects

I have array, created from json:
var array = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name2","group":"group2","id":"456", ...},
{"name":"name3","group":"group1","id":"789", ...}];
After I get another array:
var array1 = [{"name":"name1","group":"group1","id":"123", ...},
{"name":"name4","group":"group1","id":"987", ...}]
I need to push items from second array into first, but how can I check if first array contains objects from second array?
Each object in array contain more property and some of them are created dynamically so I can't check for example by indexOf(). All solutions that I found works only with simple objects like Int. It will be great if I could check by property "id" for example.
Use find first
var newObj = {"name":"name2","group":"group2","id":"456"};
var value = array.find( s => s.id == newObj.id );
Now push if the value is not found
if ( !value )
{
array.push( newObj )
}
(More generic)you can do this one line using following (which will add all object which is not in array).
array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
var array = [{"name":"name1","group":"group1","id":"123"},
{"name":"name2","group":"group2","id":"456" },
{"name":"name3","group":"group1","id":"789"}];
var array1 = [{"name":"name1","group":"group1","id":"123"},
{"name":"name4","group":"group1","id":"987"}];
array=array.concat(array1.filter(x=>!array.find(s=>s.id==x.id)));
console.log(array);

How to do a basic javascript loop / accessing array data

I have been searching A LOT to find a simple way to loop through an array (I haven't used javascript much) and I just can't seem to make sense of the examples I've seen.
I also want to retrieve data from an array...
The following example I can understand:
https://www.w3schools.com/js/js_loop_for.asp
But it's just not useful for the use case I want it for.
Say I have an array that looks like this:
array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
Question 1: How can I access the first object in that array, i.e. where the 'key' = 1?
Question 2: How can I then loop through the "values" from this object?
e.g. In Python I would do something like:
get_first_object = array1[0]
for value in array1['values']:
print value
How can I do this kind of coding in javascript?
Edit
I didn't mention this properly
My "array1" is coming from a Python view and so the output of this is different to a standard JS array (see output of console.log below):
["[{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values':["two", "2"]}]"]
so when I do var object = array1[0] I get the following output:
[{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values': ["two", "2"]}]
It doesn't seem to be getting the first object but rather seeing the whole thing as one object.
Also
I require to get this dynamically - so I can't actually hard code "array1[0]" or "array1[1]" - How can I do this?
How I am defining the array
var array1 = ["{{ my_array_1|safe }}"];
Edit 2
The way I wish to get the object from the array is like so:
var selected_id = 1;
var selected_object = array[key=selected_id];
Let's assume that your array is this:
var array = [{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values': ["two", "2"]}];
This is an array which contains javascript objects, each with 2 properties, 'key', whose corresponding value is an integer and 'values' whose corresponding value is an array of data. If I understand this correctly, you want, given an integer input_id, to access the aforementioned array of data.
function access_data (id) {
for(let obj of array){
if(obj['key'] == id){
return obj['values'];
}
}
}
If you are familiar with python you probably recognize the for .... of syntax, since it's basically the same as python's for .... in. The above code assumes that your array is a global variable called array. Calling the function with an integer argument loops through every object your array contains, checks if its 'key' property matches the given id, and if it does, the corresponding array of data is returned.
More details on for ... of loops here
This self explanatory code should rectify your doubts
var array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}];
// First Object
var firstObject = array1[0];
console.log("First object", firstObject);
// Accessing key property of first object
var keyOfFirstObj = firstObject.key;
console.log("Key", keyOfFirstObj);
// Iterating through all the values of first object
Object.values(firstObject).forEach(
el => console.log("Value -- ", el)
)
You can hardcode it: array1[0].key // 1
Use forEach to loop over:
const array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
array1.forEach(arrItem => console.log(arrItem))
Or map over it if you intend to change datas as #str said below:
const array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
array1.map(arrayItem => console.log(arrayItem);
On mapvs forEach:
https://codeburst.io/javascript-map-vs-foreach-f38111822c0f
There are a few ways to do this, the basic for loop and the for..of loop
for
for (let i = 0; i < array1.length; i++) {
console.log(array1[i])
}
for..of
for (const val of array1) {
console.log(val)
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
if you want to select an object that has a key property of "1", you could loop through the array using the methods above, returung when that condition is true, or you could use Array#filter
const filtered = array1.filter(item => item['key'] === 1) //=> returns a new array
const myObj = filtered[0]
If you want a similar syntax to Python, you Coups use the for...in loop:
let get_first_object = array1[0];
for (let index in array1['values']){
console.log(array1['values'][index]);
}
Edit:
As for your edit, you need 2 loops
let objectArray= array1[0];
if(objectArray){
for(let outerIndex in objectArray){
for(let innerIndex in objectArray[outerIndex]['values']){
console.log(objectArray[outerIndex]['values'][innerIndex];
}
}
}
Edit:
let objectArray= array1[0];
if(objectArray){
let valuesObject=objectArray.filter(f=>f.key===selectedId);
for(let innerIndex in valuesObject['values']){
console.log(valuesObject ['values'][innerIndex];
}
}
}

Convert and calculate an array javascript

I have an array like the one you can see in the pic. I have seen array with objects in it, array with numbers and/or strings. But I don't know how to deal with this kind of array. It looks like each line is an object in the array but there is no "{}". (Sorry, I am new to javascript)
My question is..I want a new array like below, how can I convert it?
newArray = [
{
time:Q2.14,
percent:...
},
{
time:Q3.14,
percent:...
},
{
time:Q4.14,
percent:...
},
....
]
The percent is the value for the current time devided by sum of all numbers.
Appreciate!
That's not really an array. It's an object with sub-objects.
var outputArray = [];
for( var prop in notQuiteArray ) {
outputArray.push({time: prop, percent: notQuiteArray[prop]});
}
where notQuiteArray is the object you were inspecting.

How to initialize 4d array in javascript?

Here is my code:
var arr = [[[[[]]]]];
var c = 20;
for (i=0;i<5;i++)
arr[i][0][0][0] = c;
alert(arr[2][0][0][0]);
It doesn't work, but how can I do this?
Most people here are using for loops, which I think are mostly obsolete in the age of anonymous functions in JavaScript. You people should know better :P
Anyway, you can solve this quite nicely in a one-liner. Here are a few scripts that can initialize your array...
If you already have a 4-dimensional array, you can initialize it elegantly like this:
arr.forEach(function(e) { e[0][0][0] = c })
Or, if you're more into map:
arr.map(function(e) { e[0][0][0] = c })
These are assuming you already have c defined, which you do in your code sample (20).
From now on, though, please Google your questions before asking them on stackoverflow. You will receive an answer that has already been accepted :)
It doesn't work because you haven't specified any elements beyond the first one, so the length of array is one and accessing further keys is incorrect.
I think, the most convenient way would be to push a new 3d array with c inside on every iteration (actually I have no idea what you're trying to achieve with this xD):
var arr = [];
var c = 20;
for (i=0;i<5;i++)
arr.push([[[c]]])
alert(arr[2][0][0][0]);
(in your example it's actually 5d, but as you've asked for 4d, writing 4d there)
It is unclear what you want, but I imagine a 4 dimension array is an array that has a set of arrays nested 3 deep, each of which has an array nested 2 deep, each of which has a single array that contains values.
In a one dimension array, you access the value at index 2 by:
arr[2];
In a two dimension array, you'd access the value at (2,3) by:
arr[2][3]
and so on until you get to the value at (2,3,1,2) in a four dimension array by:
arr[2][3][1][2]
and if that was the only value in the array, it would look like:
[,,[,,,[,[,,'value at 2312']]]];
If there was also a value at (1,1,0,2) the array would now look like:
[,[,[[,,'value at 1102']]],[,,,[,[,,'value at 2312']]]];
There can only be values in the last nested array, the value at indexes in every other array must be another array (for the lower dimensions), so to insert at value at, say (2,1,3,1) and assign it a value of 6, you need to loop over the array and inspect each index. If it's not already an array, insert an array and keep going, e.g.:
// Insert value in arrary at coord
// coord is a comma separated list of coordinates.
function insertValue( array, coord, value) {
var coords = coord.split(',');
var arr = array;
for (var c, i=0, iLen=coords.length-1; i < iLen; i++) {
c = coords[i];
if (!Array.isArray(arr[c])) arr[c] = [];
arr = arr[c];
}
arr[coords[i]] = value;
return array;
}
document.write('result: ' + JSON.stringify(insertValue([],'1,2,1,3','at 1213')));
I don't understand what you are trying to do in the OP: are you trying to create a value of 20 at coordinates (0,0,0,0), (1,0,0,0), (2,0,0,0), etc.? If that is the case, you also need a fill function that will iterate for the required number of times and pass suitable arguments to insertValue.
If that's what you want, then given the above you should be able to write such a function. On the first iteration it would pass:
insertValue(array, '0,0,0,0', 20)
and on the second:
insertValue(array, '1,0,0,0', 20)
and so on. You may wish to modify the function so that instead of the coords being a CSV string, you pass an array like [0,0,0,0] (which is what split turns the CSV string into), but that's up to you.
Note that you must pass all 4 dimensions, otherwise you will replace one of the dimension arrays with a value and effectively delete all other points in that dimension sector.
PS
ES5 introduced forEach, which helps encapsulate loops but doesn't necessarily mean less code, or faster execution, than an equivalent for loop:
// Insert value in arr at coord
// coord is a comma separated list of coordinates.
function insertValue( array, coord, value) {
var arr = array;
var coords = coord.split(',');
var last = coords.pop();
coords.forEach(function(c) {
if (!Array.isArray(arr[c])) arr[c] = [];
arr = arr[c];
})
arr[last] = value;
return array;
}
Create array with 5 nested arrays:
var arr = [[[[[]]]], [[[[]]]], [[[[]]]], [[[[]]]], [[[[]]]], [[[[]]]]];
var c = 20;
for (i=0;i<5;i++)
arr[i][0][0][0] = c;
alert(arr[2][0][0][0]);
EDIT: if you dig into functional programming and recursion, you can initialize your multidimensional array with just a few lines of code. Let's say you want 4-dimensional array with length 10 of each dimension:
function createNDimensionalArray(n, length) {
return n === 1
? new Array(length)
: Array.apply(null, Array(length)).map(createNDimensionalArray.bind(null, n - 1, length));
}
var arr = createNDimensionalArray(4, 10);
console.log(arr); // creates 4-dimensional array 10x10x10x10
Notice that initialization like this could be very slow if you create very big arrays (e.g. createNDimensionalArray(5, 10000).
If you prefer to set length of each dimension, you can modify previous the solution like this:
function createNDimensionalArray(dims) {
return dims.length === 1
? new Array(dims[0])
: Array.apply(null, Array(dims[0])).map(createNDimensionalArray.bind(null, dims.slice(1)));
}
var arr = createNDimensionalArray([2, 3, 4, 5]);
console.log(arr); // creates 4-dimensional array 2x3x4x5

JQuery Array To Re-arranged JSON object

I want to covert this javascript Array
[
"Data",
[
"API",
"Apiales",
"Apiaceae",
"Apia",
]
]
to this rearranged json Format
[
{"name":"API","id":"1"},
{"name":"Apiales","id":"1"},
{"name":"Apiaceae","id":"1"},
{"name":"Apia","id":"1"}
]
Thanks
update:
i have tried this
var aNewData =[];
for(i in aData[1]){
var item={};
item.name = aData[1][i];
item.id = "1";
aNewData[i]=item;
}
Where do the ids come from? Test following script, your array is in aData and the result will be in aNewData:
var aNewData = [];
for (var i = 0; i < aData[1].length; i++) {
aNewData.push({
"name": aData[1][i],
"id": 20 + i
});
}
Also see this example.
You might easily transform those data via folding:
var sourceData = ["API","Apiales","Apiaceae","Apia"];
var transformed = sourceData.reduce(function(result, name, index) {
return result.concat({
name: name,
id: 20 + index
});
}, []);
This will give you essentially the same, as the for loop of scessor, but in a more data-centric way.
Think of it like this:
You hold your source data (the array with all those "api*" strings)
You create a fresh resulting array [] (passed as 2nd argument to the reduce), which should be returned as your next result.
Pass an unnamed function to reduce that will be called with 3 arguments, each time it is called, namely result, which is you recently created array, name the value of each of those "api*" strings, and index, which is the index of those strings within the original array.
You look at each of those "api*" strings consecutively and put a new object containing your desired data into it. As result.concat will return the whole array, you just add those
The result array containing all your data will be returned.
But just in case you wanted to be backward compatible with older browsers, I'd recommend using underscore.js for that.

Categories

Resources