Can I create an object without a name in JS? - javascript

I have a structure that looks like this:
var set_2 = {
nameofSet : 'French greetings',
category: 'languages',
cards : [
{
front : 'bonjour',
back : 'dzien dobry'
},
{
front : 'bonne nuit',
back : 'dobranoc'
},
{
front : 'bon soir',
back : 'dobry wieczor'
}
]
}
I can iterate over them in a loop like this:
var cards = set_2.cards;
for (k = 0;k<cards.length;k++) {
var frontSide = cards[k].front;
var backSide = cards[k].back;
}
Do I assume correctly that in the cards array I have a couple of objects without names?
If so, how can I push more objects like that to the cards array without giving them names? I want to create those objects in a for loop.

I'm not sure what you mean by names, but you can push more objects into the array as such:
set_2.cards.push({front: 'front', back: 'back'});

Q: Do I assume correctly that in the cards array I have a couple of
objects without names?
A: Yes, they do not have property names like object properties do, but they each have an index, like arrays have, as in 0, 1, 2.
Or rather:
set_2.cards[0]
set_2.cards[1]
set_2.cards[2]
Q: If so, how can I push more objects like that to the cards array
without giving them names?
A: As the accepted answer says:
set_2.cards.push({front: 'front', back: 'back'});
These new objects that you push into the array will not have names, but they will have indices(or "indexes").
In summation, an element of an array is indicated by its index number(JavaScript Number), while an entry in an object is indicated by its property name(JavaScript String).

You can't create an object without names in it. Either object with names or just a normal array but you can create object with name followed by arrays inside.
Object -> object_name -> Array -> object -> object_name -> Array
var set_2 = {
nameofSet : 'French greetings',
category: 'languages',
cards : [
{
front: ['bonjour', 'bonne nuit', 'bon soir'],
back: ['dzien dobry', 'dobranoc' 'dobry wieczor']
}
]
}
'bonjour'
console.log(set_2.cards[0].front[0]);
'dobranoc'
console.log(set_2.cards[0].back[1]);
push into front
set_2.cards[0].front.push('Hello');
push into back
set_2.cards[0].back.push('Hello');

You can use the push() method like this
var set_2 = {
nameofSet : 'French greetings',
category: 'languages',
cards : [
{
front : 'bonjour',
back : 'dzien dobry'
},
{
front : 'bonne nuit',
back : 'dobranoc'
},
{
front : 'bon soir',
back : 'dobry wieczor'
}
]
}
var cards = set_2.cards;
var obj = { front:"front1", back:"back1"};
cards.push(obj);
for (k = 0;k<cards.length;k++) {
var frontSide = cards[k].front;
var backSide = cards[k].back;
console.log(backSide);
}

Regarding the question about having a few objects without names. If I understand it correctly, you have one main object. Its name is "set_2". The rest such as "nameofSet", "category", and "cards" are the names of properties of the object.
"cards" has an array value that appears to have empty objects with the "front" and "back"properties, if you are asking this*.

Related

Mapping Array Of Objects By Key

I have two arrays created from a reduce method that searches two existing arrays for dates. It then turns those dates into unique object keys.
The first group is a list of names the second is a set of series of instructions.
The goal is to combine the two arrays that get formed by finding like object keys and adding the matching list object and insert it into the set of instructions with the object key list.
For one it makes an array that looks like :
const listObj = [
{11/20/2020: [{name:'Joe', date:11/20/2020}]},
{11/26/2020 : [{name:'John', date:11/26/2020}]}
]
And this:
const scheduleObj = [
{11/20/2020: {type:'Federal', date:11/20/2020}},
{11/26/2020 : {type:'State', date:11/26/2020}}
]
The final product that i need would look something like:
const scheduleObj = [
{11/26/2020 : {
type: 'State',
list: [{name:'John', date:11/26/2020}]
},
...
]
Where the list is an added key and the array is the array that is associated with the object key
I have used a messy what looks like lodash method to get this to work, but I figure there has to be some sort of mapping I can do.
Any Help Would Be Appreciated
This can be little messy and not failure proof depending on what you have in your listObj or scheduleObj. E.g. repeated date in scheduleObj can lead to a problem using this method, you may have to use another key if the dates are no unique in both lists.
scheduleObj.map((s) => {
// get the first key of the object as the date you're going to group with
const date = Object.keys(s)[0];
// filter the object that matches the date
const listObjFilter = listObj.filter((o) => Object.keys(o)[0] === date);
// get the list for the given date (or empty array if nothing found)
const listForDate = listObjFilter.length ? listObjFilter[0][date] : [];
// build the result object
return {
[date]: {
type: s[date]['type'],
list: listForDate
}
};
})
Note that I'm always considering you have only one key in the objects inside the lists in listObj or scheduleObj.

How to map an object of arrays with Javascript

I need to map an object of arrays. Once mapped I want to display the first row of content in a div. I have an object of arrays coming from the db and I'm only mapping 2 of the 4 arrays within the object.
What I want to be able to do is use the mapped arrays and then get all the data that corresponds with that mapped array and display it all in a div. The user can click an up or down arrow and then change what is displayed, but I'm having trouble getting it to show the next or prev data in the object. I have the clicking function properly set up (worked with test data) just think it's not working because I'm not mapping it correctly.
Original object coming from db:
object: {
PageNum: [array of items],
RowNum: [array of items],
CustomerName: [array of items],
FacilityName: [array of items]
}
mapping the arrays:
var delDS = [{
pageNum : delPageData["PageNum"],
rowNum : delPageData["RowNum"]
}];
var delMappedArray = delDS.map(function(obj) {
var rObj = {};
rObj[obj.pageNum] = obj.rowNum;
return rObj;
});
which returns something like this:
[object]
0: Object
2,2,4,4,6: Array(5)
0: "24"
1: "26"
2: "2"
3: "4"
4: "10"
length: 5
Try something like this:
//map the data
delPD = delPageData.PageNum.map((x,i) => ({
pageNum: x,
rowNum: delPageData["RowNum"][i],
cName: delPageData["CustomerName"][i],
fName: delPageData["FacilityName"][i],
}));
//sort the data
delPD.sort(function(a,b) {
if(a.pageNum == b.pageNum) {
return (a.rowNum - b.rowNum);
} else {
return (a.pageNum - b.pageNum);
}
});
//give the data an index number for ordering purposes later
for(var i=0; i<delPD.length; i++) {
delPD[i].index = i;
}
This is first mapping the array of objects and creating a new array. Then you are sorting the new array by page numbers and putting them in order. Then you're adding an index number to each object. This way you can use it later in your code if need be.
Hope this helps!

Sorting only one property inside an array based on another property

I have a Javascript array that has 2 properties id, sortedPosition.
I want to kind of fake sort the array based on id, and modify sortedPosition such that it reflects the sorted position of the object within that array.
For example:
Input array:
[
{
"id" : 34,
"sortedPosition" : 2
}, {
"id" : 3,
"sortedPosition" : 1
}, {
"id" : 344,
"sortedPosition" : 0
}
]
Output array:
[
{
"id" : 34,
"sortedPosition" : 1
}, {
"id" : 3,
"sortedPosition" : 0
}, {
"id" : 344,
"sortedPosition" : 2
}
]
I came upon a solution which looks pretty bad, it involves 2 extra copies of deepCloned arrays, and it doesn't seem right. There has to be a more elegant solution.
Thanks for any help.
I came upon a solution which looks pretty bad, it involves 2 extra copies of deepCloned arrays
A shallow copy of the array should be enough:
arr.slice() // create new array with the same objects
.sort(function(a,b){return a.id-b.id;}) // sort that (leave original untouched)
.forEach(function(o,i){o.sortedPosition = i;}); // update the objects
Sort the array and then update the position.
array.sort(function(a1, a2) {
return a1.id - a2.id;
});
array.forEach(function(v, i) {
v.sortedPosition = i;
});
edit if you just want to set the sorted position, you can do something like this:
var t = array.map(function(v) {
return { v: v }
});
t.sort(function(v1, v2) { return v1.v.id - v2.v.id; });
t.forEach(function(v, i) { v.v.sortedPosition = i; });
That makes a new array with references to the objects in the original array, then sorts it, then fixes up the position properties. The ordering of the original array is unaffected. The pass to make a new array won't be very expensive; it's not really a "deep copy" at all.

Underscore.js, get two items from an object and add to the top

I have an object that looks like this
{
"AF" : {
"name" : "Afghanistan"
},
"AL" : {
"name" : "Albania"
}
}
It has objects for all countries.
What I would like to do is copy the objects from certain ISO's and add them to the top of the object (without removing the original).
What I started to do is this:
var filtered = _.collect(data, function(item, key){
if($.inArray(item.iso, ['US','CA']) !== -1) {
return item;
}
});
This gives me an array, with the objects. But, how would I add these to the original object?
Thank you!
As #mu-is-too-short said, JS objects have no mandatory ordering of their properties.
Also, your objects' properties don't have an iso property, which you're depending upon.
Please edit your question once you've seen that :)
If your code is depending on that, you're going the wrong way. As he suggests, you should use an array instead, but you can keep the objects inside of it. I'll suppose you start with a structure of the object literal shown first in your question. With this snippet, you'll be creating an array with the default order, and then adding the filtered objects to the head of that array:
var data = {
"AF" : {
"name" : "Afghanistan"
},
"AL" : {
"name" : "Albania"
}
};
var countries = _.collect(data, _.identity);
var repeated = [];
_.forEach(countries, function(country) {
if (repeatsAtTheTop(country)) {
// Added in reverse order so it preserves the
// original once unshifted into the original array
repeated.unshift(country);
}
});
_.forEach(repeated, function(item, index) { countries.unshift(item) });

Javascript defining array. "arrayception"

I am trying to create a list of "items" in a canvas game. For example, an array named list. Each element must contain the information about each item. First element will contain something different. I will remove first one with 'shift()' command. Like :
list.shift();
list[0]['name']
list[0]['id']
list[0]['x']
list[0]['y']
list[1]['name']
list[1]['id']
list[1]['x']
list[1]['y']
but i don't know how to define something like this. normally i define arrays like
{"name" : xx, "id" : 5 ... }
but this works like :
list['name']
list['id']
use:
var list = [];
list[0] = {name: 'xx', id: 0, /*etc*/};
list[1] = {name: 'yy', id: 1, /*etc*/};
it creates an array of objects. You can use it like this:
var first = list.shift();
first.name; //=> xx
//or
var first = list[0];
first.name; //=> xx
Note: using {...} (Object literal) creates an Object, not an Array. An array can be created using an Array literal: [...]. Although an object is sometimes said to be an Associative Array, it is not an Array object, so things like {...}.shift() will not work for Objects.
There are no associative arrays in javascript.
so for instance , when you do
var _array = []
_array["field1"] ="value";
you are actually adding a property to the _array object .
_array.field1 = value <=> _array["field1"] ="value";
so if you want to create a collection of objects , do
var collection =[];
var myObject = {"field1":"value1"};
collection.push(myObject);

Categories

Resources