Push an associative item into an array in JavaScript - javascript

How can I correct the following code?
var arr = [];
var name = "name";
var val = 2;
arr.push(val); //works , but not associative
arr[name] = val; //does not work
console.log(arr);
JSFiddle

To make something like associative array in JavaScript you have to use objects.
​
var obj = {}; // {} will create an object
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);
DEMO: http://jsfiddle.net/bz8pK/1/

JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);​
To get value you can use now different ways:
console.log(obj.name);​
console.log(obj[name]);​
console.log(obj["name"]);​

JavaScript has associative arrays.
Here is a working snippet.
<script type="text/javascript">
var myArray = [];
myArray['thank'] = 'you';
myArray['no'] = 'problem';
console.log(myArray);
</script>
They are simply called objects.

Another method for creating a JavaScript associative array
First create an array of objects,
var arr = {'name': []};
Next, push the value to the object.
var val = 2;
arr['name'].push(val);
To read from it:
var val = arr.name[0];

If you came to this question searching for a way to push to the end of an associative array while preserving the order, like a proper stack, this method should work. Although the output is different than the original question, it is still possible to iterate through.
// Order of entry altered
let obj = {}; // will create an object
let name = "4 name";
let val = 4;
obj[val] = name;
name = "7 name";
val = 7;
obj[val] = name;
name = "2 name";
val = 2;
obj[val] = name;
console.log(obj);
// Order of entry maintained for future iteration
obj = []; // will create an array
name = "4 name";
val = 4;
obj.push({[val]:name}); // will push the object to the array
name = "7 name";
val = 7;
obj.push({[val]:name});
name = "2 name";
val = 2;
obj.push({[val]:name});
console.log(obj);

Related

How to create key value pair using two arrays in JavaScript?

I have two arrays, keys and commonkeys.
I want to create a key-value pair using these two arrays and the output should be like langKeys.
How to do that?
This is array one:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
This is array two:
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
This is the output I need:
var langKeys = {
'en-*': 'en_US',
'es-*': 'es_ES',
'pt-*': 'pt_PT',
'fr-*': 'fr_FR',
'de-*': 'de_DE',
'ja-*': 'ja_JP',
'it-*': 'it_IT',
'*': 'en_US'
};
You can use map() function on one array and create your objects
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];
var output = keys.map(function(obj,index){
var myobj = {};
myobj[commonKeys[index]] = obj;
return myobj;
});
console.log(output);
JavaScript is a very versatile language, so it is possible to do what you want in a number of ways. You could use a basic loop to iterate through the arrays, like this:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
var i;
var currentKey;
var currentVal;
var result = {}
for (i = 0; i < keys.length; i++) {
currentKey = commonKeys[i];
currentVal = keys[i];
result[currentKey] = currentVal;
}
This example will work in all browsers.
ES6 update:
let commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
let keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT', 'en_US'];
let zipArrays = (keysArray, valuesArray) => Object.fromEntries(keysArray.map((value, index) => [value, valuesArray[index]]));
let langKeys = zipArrays(commonKeys, keys);
console.log(langKeys);
// let langKeys = Object.fromEntries(commonKeys.map((val, ind) => [val, keys[ind]]));
What you want to achieve is to create an object from two arrays. The first array contains the values and the second array contains the properties names of the object.
As in javascript you can create new properties with variales, e.g.
objectName[expression] = value; // x = "age"; person[x] = 18,
you can simply do this:
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT'];
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*'];
var langKeys = {};
var i;
for (i=0; i < keys.length; i++) {
langKeys[commonKeys[i]] = keys[i];
}
EDIT
This will work only if both arrays have the same size (actually if keys is smaller or same size than commonKeys).
For the last element of langKeys in your example, you will have to add it manually after the loop.
What you wanted to achieve was maybe something more complicated, but then there is missing information in your question.
Try this may be it helps.
var langKeys = {};
var keys=['en_US','es_ES', 'pt_PT','fr_FR','de_DE','ja_JP','it_IT']
var commonKeys=['en-*','es-*', 'pt-*','fr-*','de-*','ja-*','it-*', '*']
function createArray(element, index, array) {
langKeys[element]= keys[index];
if(!keys[index]){
langKeys[element]= keys[index-(commonKeys.length-1)];
}
}
commonKeys.forEach(createArray);
console.info(langKeys);
Use a for loop to iterate through both of the arrays, and assign one to the other using array[i] where i is a variable representing the index position of the value.
var keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];
var commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
var langKeys = {};
for (var i = 0; i < keys.length; i++) {
var commonkey = commonKeys[i];
langKeys[commonkey] = keys[i];
}
console.log(JSON.stringify(langKeys));
let keys = ['en_US', 'es_ES', 'pt_PT', 'fr_FR', 'de_DE', 'ja_JP', 'it_IT'];
let commonKeys = ['en-*', 'es-*', 'pt-*', 'fr-*', 'de-*', 'ja-*', 'it-*', '*'];
// declaration of empty object where we'll store the key:value
let result = {};
// iteration over first array to pick up the index number
for (let i in keys) {
// for educational purposes, showing the number stored in i (index)
console.log(`index number: ${i}`);
// filling the object with every element indicated by the index
// objects works in the basis of key:value so first position of the index(i)
// will be filled with the first position of the first array (keys) and the second array (commonKeys) and so on.
result[keys[i]] = commonKeys[i];
// keep in mind that for in will iterate through the whole array length
}
console.log(result);

How To Get Multiple Array Value Based On Another Array In Javascript

I don't know what must be title for my question, I think it's so complicated. So, I have A array:
["87080207", "87101133", "91140156"]
And B Array:
["97150575", "97150575", "90141063"]
This B array, I put on html select value. Each of them(A and B array) is related. I need to show 87080207,87101133 (A array) when I choose value 97150575 (B array).
I have tried, but it didn't work.This is my code:
var a=[];
var b=[];
var arrayLength = dataComponentValuation.length;
for (var i = 0; i < arrayLength; i++) {
a.push(dataComponentValuation[i].valuated);
b.push(dataComponentValuation[i].valuator);
}
var ajoin = a.join();
var bjoin = b.join();
$('#valuatedEmpCompId_before').val(ajoin);
$('#valuator_before').val(bjoin);
In select, I put a function, this is it:
function emptyValuated() {
var valby = $("#valBy").val(); //chosen value from select
var b_valby = $("#valuator_before").val();
var b_valuated = $("#valuatedEmpCompId_before").val();
if(b_valby != ''){
if(valby != b_valby)
{
$("#valuatedEmpCompId").val('');
}
else{
$("#valuatedEmpCompId").val(b_valuated);
}
}
else{
$("#valuator_before").val(valby);
$("#valuatedEmpCompId").val(b_valuated);
}
}
Help me please...
As suggested, you could use an object as reference to the values of array A.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
object = Object.create(null);
arrayB.forEach(function (b, i) {
object[b] = object[b] || [];
object[b].push(arrayA[i]);
});
console.log(object);
I guess nowadays the Map object is a perfect solution for these jobs.
var arrayA = ["87080207", "87101133", "91140156"],
arrayB = ["97150575", "97150575", "90141063"],
myMap = arrayB.reduce((p,c,i) => p.has(c) ? p.set(c, p.get(c).concat(arrayA[i]))
: p.set(c,[arrayA[i]])
, new Map());
console.log(myMap.get("97150575"));
console.log(myMap.get("90141063"));

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

push array object into localstorage

var arr = [];
var obj = {};
obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;
arr.push(obj);
localStorage.setItem('buy',JSON.stringify(arr));
The problem with above code is when executing it will replace the existing array object, how to add new obj into the array if the order_id is not the same?
New Answer:
var arr = [];
var obj = {};
obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;
$change = 'no'; for(i=0; i<arr.length; i++){ if(obj.order_id == arr[i].order_id){ obj.qty = obj.qty + arr[i].qty; arr[i] = obj; $change ='yes'; } }
if($change == 'no'){ arr.push(obj); }
console.log(arr);
And for saving it in localstorage see my answer here: push multiple array object into localhost?
Old Answer:
The best solution would be to make 'arr' an object with the order_id being the key of the object. You get something like this:
var arr = {};
var obj = {};
obj.order_id = 1;
obj.name = "Cake";
obj.price = "1 Dollar";
obj.qty = 1;
arr[obj.order_id]= obj;
console.log(arr);
This will only replace the order if the order_id is the same. If you really want and array, you have to make a function that goes through the array and checks every order_id.

How to parse bracket tag on Javascript

I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]​​​';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.

Categories

Resources