Array inside a JavaScript Object? - javascript

I've tried looking to see if this is possible, but I can't find my answer.
I'm trying to get the following to work:
var defaults = {
'background-color': '#000',
color: '#fff',
weekdays: {['sun','mon','tue','wed','thu','fri','sat']}
};
It just gives an error, and I've tried using ({...}) and [{...}] I'd like to be able to access the weekdays using something like:
defaults.weekdays[0];
is this possible?

Kill the braces.
var defaults = {
backgroundcolor: '#000',
color: '#fff',
weekdays: ['sun','mon','tue','wed','thu','fri','sat']
};

// define
var foo = {
bar: ['foo', 'bar', 'baz']
};
// access
foo.bar[2]; // will give you 'baz'

var data = {
name: "Ankit",
age: 24,
workingDay: ["Mon", "Tue", "Wed", "Thu", "Fri"]
};
for (const key in data) {
if (data.hasOwnProperty(key)) {
const element = data[key];
console.log(key+": ", element);
}
}

If you are so organised you may declare the entire object from the outset (this comma-delimited list is called an object initializer):
const myObject = {
string: 'Galactic Rainbows',
color: 'HotPink',
sociopaths: [ "Hitler", "Stalin", "Gates" ]
}
Alternatively, once you have declared the object,
// this line is the declaration:
const myObject = {};
// it is equivalent to:
const myObject2 = new Object();
you may define its properties by giving them values:
myObject.string = "Galactic Rainbows";
myObject.color = "HotPink";
myObject.sociopaths = [ "Hitler", "Stalin", "Gates" ];
// ^properties ^values
All examples below assume the object is already declared (as above)
I prefer to declare the array separately, like this, and then assign it to the object:
const weekdays = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
myObject.weekdays = weekdays;
myObject.weekdays[0]
// => 'sun'
But if you have already declared the object, it would be quicker to code:
myObject.weekdays = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
But you cannot assign an array of arrays to the object like this:
myObject.girlsAndBoys[0] = [ "John", "Frank", "Tom" ]; //Uncaught TypeError: Cannot set property '1' of undefined
myObject.girtsAndBoys[1] = [ "Jill", "Sarah", "Sally" ]; //Uncaught TypeError: Cannot set property '1' of undefined
To assign a two dimensional array to an object you have a few options. You can initialise the empty 2D array first:
myObject.girlsAndBoys = [[]];
myObject.girlsAndBoys[0] = [ "John", "Frank", "Tom" ];
myObject.girtsAndBoys[1] = [ "Jill", "Sarah", "Sally" ];
Or you may do it layer by layer:
const boys = [ "John", "Frank", "Tom" ];
const girls = [ "Jill", "Sarah", "Sally" ];
myObject.girlsAndBoys = [[ boys ],[ girls ]];
Alternatively you may do it all at once (after no more than the object declaration):
const myObject = {};
myObject.girlsAndBoys = [[ "John", "Frank", "Tom" ],
[ "Jill", "Sarah", "Sally" ]];
myObject.girlsAndBoys[0][0] == "John"; // returns True

var defaults = {
"background-color": "#000",
color: "#fff",
weekdays: [
{0: 'sun'},
{1: 'mon'},
{2: 'tue'},
{3: 'wed'},
{4: 'thu'},
{5: 'fri'},
{6: 'sat'}
]
};
console.log(defaults.weekdays[3]);

var obj = {
webSiteName: 'StackOverFlow',
find: 'anything',
onDays: ['sun' // Object "obj" contains array "onDays"
,'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
{name : "jack", age : 34},
// array "onDays"contains array object "manyNames"
{manyNames : ["Narayan", "Payal", "Suraj"]}, //
]
};

In regards to multiple arrays in an object. For instance, you want to record modules for different courses
var course = {
InfoTech:["Information Systems","Internet Programming","Software Eng"],
BusComm:["Commercial Law","Accounting","Financial Mng"],
Tourism:["Travel Destination","Travel Services","Customer Mng"]
};
console.log(course.Tourism[1]);
console.log(course.BusComm);
console.log(course.InfoTech);

Related

JAVASCRIPT: pass json key's name as parameter, and use the parameter to get the value

In javascript, is there a way to treat a JSON keyname as a variable?
For instance, below I want to perform (any set of actions) on the value of a different key in JSON each time, by telling it which json key to get by feeding the keyname to the function as a parameter.
The basic idea here is: Make a function to do (x) no matter what JSON it's given. I just need to tell it what key I want.
var myObj = {name: "John", age: 31}; // dataset #1
var myObj2 = {month: "January", day: 20}; //dataset #2
function myFunction(jsonName, variableKeyName) {
var variableKeyValue = jsonName + "." + variableKeyName; //wrong way to do this, apparently.
console.log(variableKeyValue);
}
myFunction("myObj", "name"); //want this to log "John", not the string "myObj.name".
myFunction("myObj2", "day"); //want this to log "20", not the string "myObj2.day".
Is this possible? How do get the function to assign the VALUE of the string I'm building with the parameter, rather than just the string as "jsonNameX.variableKeyNameX"?
const myObj = {name: "John", age: 31}; // dataset #1
const myObj2 = {month: "January", day: 20}; //dataset #2
function myFunction(json, variableKeyName) {
const variableKeyValue = json[variableKeyName];
console.log(variableKeyValue);
}
myFunction(myObj, "name"); // this log "John"
myFunction(myObj2, "day"); // this log 20
or you can access to global context using "this" keyword and variable name (instead variable identifier == reference)
const myObj = {name: "John", age: 31}; // dataset #1
const myObj2 = {month: "January", day: 20}; //dataset #2
function myFunction(jsonName, variableKeyName) {
const variableKeyValue = this[jsonName][variableKeyName];
console.log(variableKeyValue);
}
myFunction("myObj", "name"); // this log "John"
myFunction("myObj2", "day"); // this log 20
Yes you can do it. You can get the JSON value like this:
jsonName.variableKeyName;
but you can also get it like this:
jsonName["variableKeyName"];
(https://www.w3schools.com/js/js_json_syntax.asp)
So you can change your code in this way:
var myObj = {name: "John", age: 31}; // dataset #1
var myObj2 = {month: "January", day: 20}; //dataset #2
function myFunction(jsonName, variableKeyName) {
var variableKeyValue = jsonName[variableKeyName];
console.log(variableKeyValue );
}
myFunction(myObj, "name"); //this prints "John"
myFunction(myObj2, "day"); //this prints "20"

How to spread this array object?

I have the following object:
const info = [{ name: 'John', address: 'america', gender: 'Male', job: 'SE' }];
And I need to spread this array object and get this as
form:{
name:"John",
address:"america",
gender:"Male",
job:"SE"
}
How can I do that?
You don't need spread for that unless you want to make a shallow copy of the object. Instead, just use the object that's in the array:
const form = info[0];
or as a property on an object:
const obj = {form: info[0]};
At that point, form/obj.form and info[0] are both pointing to the same object.
If you do want to make a shallow copy, then spread is useful:
const form = {...info[0]};
or
const obj = {form: {...info[0]}};
There, form/obj.form points to a new object that has a copy of info[0]'s properties.
You could destructure the array and take the wanted property as target.
const
info = [{ "name": "John", "address": "america", "gender": "Male", "job": "SE" }],
result = {};
[{ ...result.form }] = info;
console.log(result);

How can I know how many matches I have between two arrays (one nested inside an object)?

I need to know how many matches I have between people.compare array and names array, then create a new object including this data.
names = [ 'Juan', 'Old']
people = [
{compare: ['Juan', 'Old'], Age: 70},
{compare: ['Juan', 'Young'], Age: 20}
]
Expected output:
peopleNew = [
{compare: ['Juan', 'Old'], 'Age': 70, 'MATCHES': 2},
{compare: ['Juan', 'Young'], 'Age': 20, 'MATCHES': 1}
]
This code loops through each array and uses Array.includes() to check each item for equality:
const peopleNew = people.map(obj => {
let matches = 0;
obj.compare.forEach(name => {
if (names.includes(name)) {
matches++; // Increase count by 1
}
})
// Create new object from original with new 'matches' property
return Object.assign({}, obj, { matches });
});

select value from object in javascript

Hi I am getting dificulties to select value from this dictionary,
my object
[{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
4fd5ee28-835d-42dc-85a6-699a37bc1948: "54",
f45827c8-1b1a-48c3-831b-56dab9bcaf3b: "543"
},
saved: true}]
I need to get cost of 54 somehow.
please help
<script>
var arraylist = [{'id': "063f48d0-1452-4dad-8421-145820ddf0f8",
'storeName': "birr",
'cost': {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
'saved': true}];
var costKey = '4fd5ee28-835d-42dc-85a6-699a37bc1948'
var selectedCost = arraylist[0]['cost'][costKey];
alert(selectedCost);
</script>
Your GUIDs in cost need to be inside quotes.
var obj = [{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
saved: true
}]
document.write(obj[0].cost['4fd5ee28-835d-42dc-85a6-699a37bc1948']);
That outputs the value 54.
Make sure your keys are in quotes. Otherwise to retrieve the value it is simply a matter of accessing it like object[key] as the following code demonstrates.
var stores = [{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
saved: true
}];
var store = stores[0];
var cost = store.cost;
var key = Object.keys(cost)[0];
var value = cost[key];
console.log(value);

How to optimize array lookup of JS object based on one property

We have a large array of objects:
var englishStudents = [
{StudentId: 1, Name: "John"},
{StudentId: 2, Name: "Jack"},
{StudentId: 3, Name: "Jane"}
];
Need to check if another similar object is contained in this array, just by comparing one property alone.
var randomStudent = {StudentId: 1337, Name: "Foo"};
This is what I have, and it seems as though it will work, but I don't think this is the best way to do this.
var studentIds = $.map(englishStudents, function (student, index) { return student.StudentId; });
var randomStudentLearnsEnglish = false;
for (var sId in studentIds) {
if (randomStudent.StudentId == sId) {
randomStudentLearnsEnglish = true;
break;
}
}
What would be the optimized way to do this?
You should keep student data in a hash table like JHashtable instead of the array. For mor complex scenarios, you can maintain more than one hash table, like studentsById, studentsByCountryCode, etc.
If all you want to know is if the ID exists can do this:
function checkIdExists( id){
/* map array of matching ID, if none exists length of array is zero*/
return $.map(englishStudents, function (student, index) {
return student.StudentId==id;
}).get().length;
});
Use:
if( checkIdExists( 1234)){
/* run exists code*/
}
If you really want, you can create a further indexing scheme:
var englishStudents = [
{StudentId: 1, Name: "John"},
{StudentId: 2, Name: "Jack"},
{StudentId: 3, Name: "Jane"}
];
//if doing this a lot of time, take the one time hit of construction and memory
var idToNameMap = createIdToNameMap(englishStudents); //returns {'1': 'John', '2': Jack' , '3': 'Jane'}
var randomStudent = getRandomStudent();
if( idToNameMap[ randomStudent.StudentId] != undefined){ ... }
Just do a hash instead of an array, so:
var englishStudents = {
1: {StudentId: 1, Name: "John"},
2: {StudentId: 2, Name: "Jack"},
3: {StudentId: 3, Name: "Jane"}
};
and then to retrieve, simply do:
var student = englishStudents[id];

Categories