This is what I have so far and the shoe types are boots, wellingtons, leather, trainers (in that order)
I want to iterate through and assign the value so I haves something like
var shoeArray = { boots : '3', wellingtons: '0', leather : '1', trainers: '3'};
at the moment I just get an array of {3,0,1,3} which I can work with but it is not very helpful.
function shoe_types() {
var shoeArray = [];
$('[type=number]').each(function(){
$('span[data-field='+$(this).attr('id')+']').text($(this).val());
shoeArray.push ( parseInt($(this).val()) );
});
return shoeArray;
}
Check this function
function shoe_types() {
var shoeArray = {}; // note this
$('[type=number]').each(function(){
$('span[data-field='+$(this).attr('id')+']').text($(this).val());
shoeArray[$(this).attr('id')] = parseInt($(this).val()) ;
});
return shoeArray;
}
PS: Assuming $(this).attr('id') has all the shoe types
Associative array in javascript is the same as object
Example:
var a = {};
a["name"] = 12;
a["description"] = "description parameter";
console.log(a); // Object {name: 12, description: "description parameter"}
var b = [];
b["name"] = 12;
b["description"] = "description parameter";
console.log(b); // [name: 12, description: "description parameter"]
What you want is a function that will return an object {}
LIVE DEMO
function shoe_types(){
var shoeObj = {};
$('[name="number"]').each(function(){
shoeObj[this.id] = this.value;
});
return shoeObj;
}
shoe_types(); // [object Object]
You can try this to create an associate array in jquery
var arr = {};
$('[type=number]').each(function(){
arr.push({
$(this).attr('id'): $(this).val()
});
});
console.log(arr);
This will allow you to send your all data whatever you want to pass in array by ajax.
if $(this).attr('id') is the type of shoes you can try that
shoeArray[$(this).attr('id')] = parseInt($(this).val());
Related
I have an empty object, and i want to push a key value pair to the array.
required.forEach(function(value){
if(value){
var tempVal = "event_info.schema." + value;
// console.log(tempVal);
var row = {tempVal: [properties[value]['type']]};
}
});
when I console.log(row) it shows
{ tempVal: [ 'string' ] }
However I want it to be the content of tempVal instead of "tempVal"
i.e. if tempVal = "name", I want row to be { name : ['string']}. How can I achieve this?
I have tried tempVal.eval() but that is an error. Can you point me to the right direction. Thanks in advance.
Objects can also be indexed with brackets.
tempVal = 'someString';
var obj = {};
obj[tempVal] = ['myArrayOfOneString'];
console.log(obj) // {'someString': ['myArrayOfOneString']}
Note that obj.something is equivalent to object['something']
This should do what you are looking for:
var
event_info = {
schema: {
name: "Yoda",
age: "150"
}
},
properties = {
name: {type: "male"},
age: {type: "old"}
}
//
var value = "name";
//
var tempVal = event_info.schema[value];
var row = {};
row[tempVal] = [properties[value]['type']];
console.log("tempVal:", tempVal);
console.log("row:", row);
console.log("row 'Yoda':", row["Yoda"]);
you will have to use array notation to set the property dynamically, like this:
var row = {};
row[tempVal] = [properties[value]['type']];
EDIT: as a commenter pointed out, you can condense this to one line (ES6 only):
var row = {[tempVal]: [properties[value]['type']]}
I have declared a JSON Object and added some key value pair in that like:
var obj = {};
and added some data into it like:
obj = {
"1":"aa",
"2":"bb"
};
But I want to add more key value pair in the same object, if I add key value pair same above mentioned then it replace the old one. So could any one please tell me how I can append data in the same JSON Object i.e. obj.
Could you do the following:
obj = {
"1":"aa",
"2":"bb"
};
var newNum = "3";
var newVal = "cc";
obj[newNum] = newVal;
alert(obj["3"]); // this would alert 'cc'
You can use dot notation or bracket notation ...
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj.another = "valuehere";
obj["3"] = "cc";
Object assign copies one or more source objects to the target object. So we could use Object.assign here.
Syntax: Object.assign(target, ...sources)
var obj = {};
Object.assign(obj, {"1":"aa", "2":"bb"})
console.log(obj)
Example code for json object:
var user = {'user':'barney','age':36};
user["newKey"] = true;
console.log(user);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
for json array elements
Example code:
var users = [
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 }
];
users.map(i=>{i["newKey"] = true});
console.log(users);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="lodash.js"></script>
Hi I add key and value to each object
let persons = [
{
name : "John Doe Sr",
age: 30
},{
name: "John Doe Jr",
age : 5
}
]
function addKeyValue(obj, key, data){
obj[key] = data;
}
let newinfo = persons.map(function(person) {
return addKeyValue(person, 'newKey', 'newValue');
});
console.log(persons);
Please try following simple operations on a json, insert/update/push:
var movie_json = {
"id": 100,
};
//to insert new key/value to movie_json
movie_json['name'] = 'Harry Potter';
console.log("new key: " + movie_json);
//to update a key/value in movie_json
movie_json['id'] = 101;
console.log("updated key: " +movie_json);
//adding a json array to movie_json and push a new item.
movie_json['movies']=["The Philosopher's Stone"];
movie_json['movies'].push('The Chamber of Secrets');
console.log(movie_json);
You can add more key value pair in the same object without replacing old ones in following way:
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj["3"] = "cc";
Below is the code and jsfiddle link to sample demo that will add more key value pairs to the already existed obj on clicking of button:
var obj = {
"1": "aa",
"2": "bb"
};
var noOfItems = Object.keys(obj).length;
$('#btnAddProperty').on('click', function() {
noOfItems++;
obj[noOfItems] = $.trim($('#txtName').val());
console.log(obj);
});
https://jsfiddle.net/shrawanlakhe/78yd9a8L/4/
possible duplicate , best way to achieve same as stated below:
function getKey(key) {
return `${key}`;
}
var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};
https://stackoverflow.com/a/47405116/3510511
I have an array into which I insert a load of values along with their corresponding keys. They are inserted fine as I can see them all in the array when I do a console.log.
The issue is, I can't seem to retrieve the values from the array using their respective keys.
Here is my code.
var personArray = [];
personArray.push({
key: person.id,
value:person
});
var personID = person.id;
console.log(personArray.personID);
I have also tried console.log(personArray[personID]; but this does not work either.
The value I get in my console is undefined.
What you are doing is that you push dictionaries into the array. If person.id is unique, then you can do this:
var personDict = {}
personDict[person.id] = person
and then personDict[personID] will work. If you want to keep your structure, then you have to search inside the array for it:
var personArray = [];
personArray.push({
key: person.id,
value:person
});
var personID = person.id;
var search = function(id) {
var l = personArray.length;
for (var i = 0; i < l; i++) {
var p = personArray[i];
if (p.key === id) {
return p.value;
}
}
return null;
};
search(personID);
You can use dictionary format as suggested by #freakish,
Or use the filter function to find the required object.
For example:
var personArray = [];
var person = {id: 'aki', value:'Akhil'}
personArray.push({
key: person.id,
value:person
});
personArray.filter(function(item){
return item.key == 'aki'
});
I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.
var sample = new Array();
sample[0] = new Object();
sample[1] = new Object();
This works fine, but I don't want to mention any index number. I want all elements of my array to be an object. How do I declare or initialize it?
var sample = new Array();
sample[] = new Object();
I tried the above code but it doesn't work. How do I initialize an array of objects without using an index number?
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
To do this n times use a for loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
Depending on what you mean by declaring, you can try using object literals in an array literal:
var sample = [{}, {}, {} /*, ... */];
EDIT: If your goal is an array whose undefined items are empty object literals by default, you can write a small utility function:
function getDefaultObjectAt(array, index)
{
return array[index] = array[index] || {};
}
Then use it like this:
var sample = [];
var obj = getDefaultObjectAt(sample, 0); // {} returned and stored at index 0.
Or even:
getDefaultObjectAt(sample, 1).prop = "val"; // { prop: "val" } stored at index 1.
Of course, direct assignment to the return value of getDefaultObjectAt() will not work, so you cannot write:
getDefaultObjectAt(sample, 2) = { prop: "val" };
You can use fill().
let arr = new Array(5).fill('lol');
let arr2 = new Array(5).fill({ test: 'a' });
// or if you want different objects
let arr3 = new Array(5).fill().map((_, i) => ({ id: i }));
Will create an array of 5 items. Then you can use forEach for example.
arr.forEach(str => console.log(str));
Note that when doing new Array(5) it's just an object with length 5 and the array is empty. When you use fill() you fill each individual spot with whatever you want.
After seeing how you responded in the comments. It seems like it would be best to use push as others have suggested. This way you don't need to know the indices, but you can still add to the array.
var arr = [];
function funcInJsFile() {
// Do Stuff
var obj = {x: 54, y: 10};
arr.push(obj);
}
In this case, every time you use that function, it will push a new object into the array.
You don't really need to create blank Objects ever. You can't do anything with them. Just add your working objects to the sample as needed. Use push as Daniel Imms suggested, and use literals as Frédéric Hamidi suggested. You seem to want to program Javascript like C.
var samples = []; /* If you have no data to put in yet. */
/* Later, probably in a callback method with computed data */
/* replacing the constants. */
samples.push(new Sample(1, 2, 3)); /* Assuming Sample is an object. */
/* or */
samples.push({id: 23, chemical: "NO2", ppm: 1.4}); /* Object literal. */
I believe using new Array(10) creates an array with 10 undefined elements.
You can instantiate an array of "object type" in one line like this (just replace new Object() with your object):
var elements = 1000;
var MyArray = Array.apply(null, Array(elements)).map(function () { return new Object(); });
Well array.length should do the trick or not? something like, i mean you don't need to know the index range if you just read it..
var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.
IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:
var arrayContainingObjects = [];
for (;;){
try{
arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}
}
catch(err){
break;
}
It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.
//making array of book object
var books = [];
var new_book = {id: "book1", name: "twilight", category: "Movies", price: 10};
books.push(new_book);
new_book = {id: "book2", name: "The_call", category: "Movies", price: 17};
books.push(new_book);
console.log(books[0].id);
console.log(books[0].name);
console.log(books[0].category);
console.log(books[0].price);
// also we have array of albums
var albums = []
var new_album = {id: "album1", name: "Ahla w Ahla", category: "Music", price: 15};
albums.push(new_album);
new_album = {id: "album2", name: "El-leila", category: "Music", price: 29};
albums.push(new_album);
//Now, content [0] contains all books & content[1] contains all albums
var content = [];
content.push(books);
content.push(albums);
var my_books = content[0];
var my_albums = content[1];
console.log(my_books[0].name);
console.log(my_books[1].name);
console.log(my_albums[0].name);
console.log(my_albums[1].name);
This Example Works with me.
Snapshot for the Output on Browser Console
Try this-
var arr = [];
arr.push({});
const sample = [];
list.forEach(element => {
const item = {} as { name: string, description: string };
item.name= element.name;
item.description= element.description;
sample.push(item);
});
return sample;
Anyone try this.. and suggest something.
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
you can use it
var x = 100;
var sample = [];
for(let i=0; i<x ;i++){
sample.push({})
OR
sample.push(new Object())
}
Using forEach we can store data in case we have already data we want to do some business login on data.
var sample = new Array();
var x = 10;
var sample = [1,2,3,4,5,6,7,8,9];
var data = [];
sample.forEach(function(item){
data.push(item);
})
document.write(data);
Example by using simple for loop
var data = [];
for(var i = 0 ; i < 10 ; i++){
data.push(i);
}
document.write(data);
If you want all elements inside an array to be objects, you can use of JavaScript Proxy to apply a validation on objects before you insert them in an array. It's quite simple,
const arr = new Proxy(new Array(), {
set(target, key, value) {
if ((value !== null && typeof value === 'object') || key === 'length') {
return Reflect.set(...arguments);
} else {
throw new Error('Only objects are allowed');
}
}
});
Now if you try to do something like this:
arr[0] = 'Hello World'; // Error
It will throw an error. However if you insert an object, it will be allowed:
arr[0] = {}; // Allowed
For more details on Proxies please refer to this link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
If you are looking for a polyfill implementation you can checkout this link:
https://github.com/GoogleChrome/proxy-polyfill
The below code from my project maybe it good for you
reCalculateDetailSummary(updateMode: boolean) {
var summaryList: any = [];
var list: any;
if (updateMode) { list = this.state.pageParams.data.chargeDefinitionList }
else {
list = this.state.chargeDefinitionList;
}
list.forEach((item: any) => {
if (summaryList == null || summaryList.length == 0) {
var obj = {
chargeClassification: item.classfication,
totalChargeAmount: item.chargeAmount
};
summaryList.push(obj);
} else {
if (summaryList.find((x: any) => x.chargeClassification == item.classfication)) {
summaryList.find((x: any) => x.chargeClassification == item.classfication)
.totalChargeAmount += item.chargeAmount;
}
}
});
if (summaryList != null && summaryList.length != 0) {
summaryList.push({
chargeClassification: 'Total',
totalChargeAmount: summaryList.reduce((a: any, b: any) => a + b).totalChargeAmount
})
}
this.setState({ detailSummaryList: summaryList });
}
var ArrayofObjects = [{}]; //An empty array of objects.
I have an array done with values from some radio buttons, say myArray = ["1","40","35"];
every value has his counterparts, say for instance 1 = "men", 2 = "women", 40 = "red hairs".
what's the best method to build another array where every values gets his counterpart?
so something like that myBrandNewArray = ["men","red hairs", …];
I should store my couples into variables for some maintenance, like
var "1" = "men", "2" = "women", … ;
but I don't know if this is a good approach…
ps. even pointing me to some resources will be great. Thank you.
I would keep a Hash of values
hash = { '1': 'Men', '2': 'Women' ... }
Then [ '1', '2', ... ].map( function(v) { return hash[v]; } );
IE9- will not accpet this, in this case you could just iterate in a for loop
Why don't you use an object as associative array?
var array = new Object();
array["1"] = "men"
array["40"] = "red hairs"
You can create an object like:
var arr = {
'1' : 'men',
'2' : 'women'
}
You can always access this easily like : arr['1'] == 'men'
if you want to create from existing arrays:
say myArray & myBrandNewArray
you can do something like
var arr = {};
foreach ( var i in myArray ) {
arr[myArray[i]] = myBrandNewArray[i];
}
i think this function
myArray = ["1","40","35"];
myBrandNewArray = myArray.map(function(element){ /* your code to get the right array 8/ })
source: http://www.tutorialspoint.com/javascript/array_map.htm
there is also a jQuery (cross browser) version of this function, for more details about that look here jQuery.map(myArray, function(value, index){ /*....*/ })
Use an object:
var val = {
1: "men",
40: "red hairs"
};
alert(val[1]);
alert(val[2])
;
well, finally I did this:
having
var numericalArray = ["1","50","45", …];
and
var couples = { "50" : "homme",
"1" : "femme",
"85" : "court",
…
};
I can call this and get a new array with coupled values:
function assignValues(numericalArray) {
var verbalArray = [];
for (var i=0; i<numericalArray.length; i++) {
var value = numericalArray[i];
verbalArray.push(couples[value]); // right, I can't check if the values exists
}
console.log('here my new array:', verbalArray);
}
thanks to have me pointed on use of an object.