How to push object into an array? in Angular 7 - arrays

I am pushing an object into an array but cannot do it?
I'm doing it like this
this.passData = this.tribeForm.value;
var id = {"tribe_id": 1}
this.passData.push(id)
This is the value in the tribeForm
I also tried
var id = {tribe_id: 1}
and
this.passData.splice(0,0, id)
and
this.passData = Array.prototype.slice(id)
and
this.passData.concat(id)
but it all ends up with
TypeError: this.passData.push/splice/concat is not a function

The question is not that clear, But I understood you are manipulating form data, value of form data returns an Object, Not an array. Objects in JavaScript are represented as key-value pairs, (or attribute-value) pairs.
Example :
var object = {
name : "Jhon",
grade : 12,
gpa : 8.12
}
It is just a collection of key-value pairs, push(), concat() and other methods are supported only for Arrays not for Objects. You can achieve whatever you want simply by creating a new key/attribute and assigning the value to it.
this.passData = this.tribeForm.value
this.passData['tribe_id'] = 1
//or, Objects can also contain nested object
this.passData['someKey'] = {'tribe_id' : 1}
You can create an empty array and push objects to it
Example :
var exampleArray = []
exampleArray.push({'tribe_id' : 1})
Now, it works because exampleArray is an Array not JS object.
Thanks for A2A

First, you need to understand the error:
TypeError: this.passData.push/splice/concat is not a function
Push/splice/concat is functions for Array and because of that the console is yelling at you that the passData is not an Array.
Make sure your passData is an Array and you will able to do so.

Related

Adding an Array to an Array in Angular

So I have a db document that holds some string values in an array, I want to push just the array from every entry into an array in the application for usage later, But I can see the array fine on the fetch, and when I iterate it but my "Global array" is staying empty can someone explain why?
specialDates : Specialdates[] = [];
specialRange: any[] = [];
this.specialDates.forEach(ag => {
//ag,range -> I can see fine
this.specialRange.push(ag.range);
//this.specialrange -> Stays empty
});
Array looks something like the following:
1205,1206,1207,1208
What is wrong with this approach?
Reason for doing this is because the documents have 2 fields minimum: EG ->
ID/Array
And I just need the array
this.specialRange = this.specialDates.map(ag => ag.range)

How prevent Object.keys() sort?

The problem with the ECMA standard for sort of Object.keys() is known:
Object.keys() handle all keys with integer (example: 168), including integer as strings (example: "168"), as a integer. The result is, both are the same (168 === "168"), and overwrite itself.
var object = {};
object["168"] = 'x';
object[168] = 'y';
Object.keys(object); // Array [ "168" ]
object[Object.keys(object)]; // "y"
Interestingly, all keys (including pure integer keys) are returned as a string.
The ecma262 wrote about this: All keys will be handle as a integer, expect the key is a String but is not an array index.
https://tc39.es/ecma262/#sec-ordinaryownpropertykeys
That should tell us: 168 === "168". A toString() do not solve the problem.
var object = {};
object[[3].toString()] = 'z';
object[[1].toString()] = 'x';
object[[2].toString()] = 'y';
Object.keys(object);
// Array(3) [ "1", "2", "3" ]
Paradoxically, in this case, only integer apply as "enumerable" (it's ignoring array.sort(), that sort also strings with letters.).
My question about this is simple: How can i prevent the sort function in Object.keys()? I have testet the Object.defineProperties(object, 1, {value: "a", enumerable: true/false}), but that mean not realy enumerable in the case of integer or string or integer-like string. It means only should it be counted with or not. It means "counted" like omit (if it false), not "enumerabled" like ascending or descending.
A answere like that is not a good answer: Please use only letters [a-zA-Z] or leastwise a letter at the first position of keyword.
What I want: That the keys are not sorted, but output in the order in which they were entered, whether integer, string or symbol.
Disclaimer: Please solutions only in JavaScript.
Javascript Objects are unordered by their nature. If you need an ordered object-like variable I would suggest using a map.
To achieve what you're looking for with a map instead of object you'd do something like the below:
var map1 = new Map();
map1.set("123", "c");
map1.set(123, "b");
var iterator1 = map1.keys();
var myarray = [];
for (var i = 0; i < map1.size; i++) {
myarray.push(iterator1.next().value);
}
console.log(myarray);
// Array ["123", 123]
Unfortunately it's not compatible with IE and I'm not sure how else you could achieve what you need without it. A quick Google did return something about jQuery maps, though.
If you don't want to use jQuery and still need to support IE some points are below:
Is there anything stopping you using an array rather than JS object to store the data you need? This will retain the order per your requirements unlike objects. You could have an object entry in each iteration which represents the key then use a traditional foreach to obtain them as an array. I.e.
The array:
var test_array = [
{key: 123, value: 'a value here'},
{key: "123", value: 'another value here'}
];
// console.log(test_array);
Getting the keys:
var test_array_keys = [];
test_array.forEach(function(obj) { test_array_keys.push(obj['key']); } );
// console.log(test_array_keys);
Then if you needed to check whether the key exists before adding a new entry (to prevent duplicates) you could do:
function key_exists(key, array)
{
return array.indexOf(key) !== -1;
}
if(key_exists('12345', test_array_keys))
{
// won't get here, this is just for example
console.log('Key 12345 exists in array');
}
else if(key_exists('123', test_array_keys))
{
console.log('Key 123 exists in array');
}
Would that work? If not then the only other suggestion would be keeping a separate array alongside the object which tracks the keys and is updated when an entry is added or removed to/from the object.
Object Keys sorted and store in array
First Creating student Object. then sort by key in object,last keys to store in array
const student={tamil:100, english:55, sci:85,soc:57}
const sortobj =Object.fromEntries(Object.entries(student).sort())
console.log(Object.keys(sortobj))
use map instead of an object.
let map = new Map()
map.set("a", 5)
map.set("d", 6)
map.set("b", 12)
to sort the keys (for example, to update a chart data)
let newMap = new Map([...map.entries()].sort())
let keys = Array.from(newMap.keys()) // ['a','b','d']
let values = Array.from(newMap.values()) // [5,12,6]

Problem Using _.compact lodash to eliminate null values on an array of objects

I'm manipulating an array of objects that i get from an http request containing coordinates to create markers in google-maps , but i need to eliminate all the null values in the array. I'm trying with compact but it gives back the same array unchanged.
//this is the resulting array structure
var array=
[{"id":0,"latitude":45.17850875854492,"longitude":7.773523330688477},{"id":1,"latitude":45.122344970703125,"longitude":7.7135162353515625},{"id":2,"latitude":null,"longitude":null},{"id":3,"latitude":45.11630630493164,"longitude":7.730717658996582},{"id":4,"latitude":45.116214752197266,"longitude":7.730687141418457},{"id":5,"latitude":null,"longitude":null}]
var comp =_.compact(array)
i dont get any error in the cosole , but the variable comp return the same exact array without removing null values
All your values are arrays, and the null is a value of your properties. The _.compact() method works with primitives.
Use _.reject() and check with _.isNull if the properties are null, and the object should be removed:
const array =
[{"id":0,"latitude":45.17850875854492,"longitude":7.773523330688477},{"id":1,"latitude":45.122344970703125,"longitude":7.7135162353515625},{"id":2,"latitude":null,"longitude":null},{"id":3,"latitude":45.11630630493164,"longitude":7.730717658996582},{"id":4,"latitude":45.116214752197266,"longitude":7.730687141418457},{"id":5,"latitude":null,"longitude":null}]
const result = _.reject(array, ({ latitude, longitude }) =>
_.isNull(latitude) || _.isNull(longitude)
)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
You can use _.pickBy()
Creates an object composed of the object properties predicate returns truthy for
lodash
This applies on object so for an array you can use that:
var comp = _.map(array, item => _.pickBy(item));

change key's value across multiple objects at once in JS

I have multiple objects that all have the same keys lets say each object has: name and position. The first object will start with position=0. The second object would have position=1. The third object would have position=2 and so on until we get to the 10th object that would have position=9.
I need a way to subtract 1 from every objects position (with only possible values being 0-9 so that 0-1=9)
Looking for a solution that handles all of them mathematically at once, not just re-writing out new values to assign to each key individually.
Suppose you have an array of JavaScript objects, you could use map:
var newObjs = objects.map(function (object) {
object.position = (object.position === 9 ? 0 : object.position--);
return object;
});
A better approach would be:
objects.forEach( function (object) {
object.position--;
object.position = object.position < 0 ? 9 : object.position;
});

Swift 3 - Get value from array of dictionaries

Trying to get the value and the key of a dictionary that's stored in an array to populate two UILabels.
My array looks as follows:
var fromLocations = [["marco" : "polo"],["jekyll" : "hide"],["freddy" : "jason"]]
I'm getting the index by a collection view's indexPath. Currently trying the following:
cell.locationName.text = fromLocations[indexPath.item].values[1]
I've tried a bunch of other ways but I can't nail it.
Is this what you are trying to do?
var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]]
let marco = fromLocations[0]["marco"]
print("marco = \(marco)")
This prints "polo1". Basically you are accessing the first item of the array which is a dictionary. You then access that dictionary the way you would normally access a dictionary.
So a break down would be:
let fromLocations = [["marco" : "polo"],["marco" : "polo"],["marco" : "polo"]]
let theDictionary = fromLocations[0]
let value = theDictionary["marco"]
To just get the values as an array with using the key (which is strange), turn the values into an array.
var fromLocations = [["marco" : "polo1"],["marco" : "polo2"],["marco" : "polo3"]]
let marco = Array(fromLocations[0].values)[0]
print("marco = \(marco)")
This will print "polo1"

Resources