Removing empty array values on multidimensional array - arrays

I want to remove arrays cctype, cctypologycode, and amount when they are empty from array. best way to do it ?
{
"ccInput": [
{
"designSummaryId": 6,
"CCType": "A",
"CCTypologyCode": "A",
"Amount": "1"
},
{
"designSummaryId": 7,
"CCType": "",
"CCTypologyCode": "",
"Amount": ""
},
]
}
ccInput[1] should be removed from the array

If you want to remove some objects from your array, use Array.prototytpe.filter().
You can do it in an immutable way by copying each property of your object using the spread operator and then filter the ccInput property:
const obj = {ccInput:[{designSummaryId:6,CCType:"A",CCTypologyCode:"A",Amount:"1"},{designSummaryId:7,CCType:"",CCTypologyCode:"",Amount:""}]};
const result = { ...obj, ccInput: obj.ccInput.filter(x => x.CCType && x.CCTypologyCode) };
console.log(result);
Or if you want to modify your object in place, simply reassign the ccInput property:
const obj = {ccInput:[{designSummaryId:6,CCType:"A",CCTypologyCode:"A",Amount:"1"},{designSummaryId:7,CCType:"",CCTypologyCode:"",Amount:""}]};
obj.ccInput = obj.ccInput.filter(x => x.CCType && x.CCTypologyCode);
console.log(obj);

I don't know much about TypeScript, but I do know you can set the array to []. However, for those of you looking to get rid of only part of an array but not all of it, the simplest way to do so that I know of is to just set each value to 0 for numbers, '' for characters, "" for Strings, etc.

Related

Compare two object arrays for equality, regardless of the order of object properties

I am trying to compare two object arrays for equality, disregarding any differences in the order of the properties. I just want to know when the values for each property match. Below are examples of one object in each array being compared, that should be equal, based on the values of each property. The ordering of the properties does not matter, along with the ordering of the "values" property values.
{
"fieldId": "123456789",
"operationType": 1,
"definitionType": 1,
"values": ["123","456"],
"isAllSelected": false,
"dateRangeSelectionType": 0
}
{
"isAllSelected": false,
"operationType": 1,
"definitionType": 1,
"fieldId": "123456789",
"values": ["456","123"],
"dateRangeSelectionType": 0
}
I have attempted to use JSON.stringify to compare these arrays, but I know this won't work since it will take the ordering into account of equality.
I also have the following helper functions that I am using for another object array, however this does not work properly for these arrays:
> const objectsAreEqual = (object1: any, object2: any) =>
> Object.keys(object1).length === Object.keys(object2).length
> && Object.keys(object1).every(index => object1[index] === object2[index]);
>
> const objectArraysAreEqual = (array1: Object[], array2: Object[]) =>
> array1.length === array2.length && array1.every((x, index) => objectsAreEqual(x, array2[index]));
First, note that I cleaned up the data a bit. In your second example object, "isAllSelected": false, appears twice which is not a valid javascript object. Also, the values array has the order of its elements swapped around which makes these actually not the same object, so for these demo examples I have them both as the exact same array.
Since you labeled this as a TypeScript question, I first made a TypeScript type for this object shape which I named "Foo".
type Foo = {
fieldId: string;
operationType: number;
definitionType: number;
values: string[];
isAllSelected: boolean,
dateRangeSelectionType: number
}
Then I defined the two objects as type Foo.
const fooA: Foo = {
"fieldId": "123456789",
"operationType": 1,
"definitionType": 1,
"values": ["123","456"],
"isAllSelected": false,
"dateRangeSelectionType": 0
}
const fooB: Foo = {
"isAllSelected": false,
"operationType": 1,
"definitionType": 1,
"fieldId": "123456789",
"values": ["123", "456"],
"dateRangeSelectionType": 0
}
Using the == and === operators are good for primitive types, but they will return "false" when comparing these objects, as will the "Object.is" function.
console.log(fooA == fooB) // false
console.log(fooA === fooB) // false
console.log(Object.is(fooA, fooB)) // false
So, looks like you will have to roll up your sleeves and go through checking every key and value in objects...
What you basically want to do is:
Make sure objects have the same keys.
Make sure those keys have the same values.
The tricky part is what happens if the values themselves are objects? In some cases you may want it to just be a shallow equals (eg. if you want your function to say they are equal even if the "values" array has different elements).
If you want the function to keep drilling down and check that EVERYTHING in the objects are the same then you want to check for "deep equality".
Here is one implementation of how you could implement this:
export default function deepEquals(object1: any, object2: any) {
const keys1 = Object.keys(object1);
const keys2 = Object.keys(object2);
if (keys1.length !== keys2.length) {
return false;
}
for (const key of keys1) {
const val1 = object1[key];
const val2 = object2[key];
const areObjects = isObject(val1) && isObject(val2);
if (
areObjects && !deepEquals(val1, val2) ||
!areObjects && val1 !== val2
) {
return false;
}
}
return true;
}
function isObject(object: Object) {
return object != null && typeof object === 'object';
}
Notice how this function returns true when comparing the objects:
import deepEquals from './deepEquals';
console.log(deepEquals(fooA, fooB)) // true
You could also use a library such as lodash that has deep object comparison:
import isEqual from 'lodash.isequal';
console.log(isEqual(fooA, fooB)) // true

How to push array value with defined object in angular

My array
let myArr=["test1","test2"];
Need to add the object like below
let myFinalArr=[["test1":{"val1":"XXX","val2":"YYY"}],["test2":{"val1":"XXX","val2":"YYY"}]];
how to push the data like above in angular.
There are multiple ways to do it. How exactly does the requirement look? Does the object remain same for all the elements in the array?
And expanding from your comment that the following is the actual output's structure
{
"test1": { "val1":"XXX", "val2":"YYY" },
"test2": { "val1":"XXX", "val2":"YYY" }
}
You could try the Array#reduce with spread operator to transform the array
let myArr = ["test1", "test2"];
const output = myArr.reduce((acc, curr) => ({
...acc,
[curr]: { val1: "XXX", val2: "YYY" }
}), Object.create(null));
console.log(output);

trying to push two specific values into another array as a key value pair using typescript

Newbie here and this is a project I'm building to learn. I'm going around in circles so forgive my ignorance please. I'm now not even sure that what I want to do is possible. I also understand that there are probably better ways to achieve my ultimate goal but this is what I have.
I have an array that includes some user input.
"participants": [ {
"name": "Cristina",
"email": "cristina#gmail",
"yourPerson": "Richard",
"spouseEmail": "Richard#gmail" } ] }
I want to pull the "name" and "youPerson" values and use them as a key:value pair. So name would be the key and yourPerson would be the value.
I thought I could use a forEach but no matter what I do I either get an undefined array or I copy the entire array, not just those two fields.
here is my code at the moment:
participantArray = [];
namePlusSpouseArray = [];
submitParticipant() {
this.participantArray.push(this.participantForm.value);
console.log(this.participantArray)
this.createNamePlusSpouseArray();
}
createNamePlusSpouseArray() {
this.participantArray.forEach(name => {
this.namePlusSpouseArray.push(this.participantArray[name]);
console.log(this.namePlusSpouseArray)
});
}
Not sure if you want a result array of key value pairs, or you want 1 object/map/dictionary/lookup of name -> youPerson
Assuming you want an array containing key value pairs, you can use map
this.namePlusSpouseArray = this.participantArray.map(participant => ({
[participant.name]: participant.youPerson
});
If you want a lookup of name -> youPerson, the "namePlusSpouseArray" shouldn´t be an array but instead just an object
namePlusSpouseLookup = {};
this.participantArray.forEach(participant => {
this.namePlusSpouseLookup[participant.name] = participant.youPerson;
});
The simplest solution is:
const participantArray = {
"participants": [ { "name": "Cristina", "email": "cristina#gmail", "yourPerson": "Richard", "spouseEmail": "Richard#gmail" } ] };
const createPair = participants => {
return participants.map(participant =>
({ [participant.name]: participant.yourPerson}))
}
console.log(createPair(participantArray.participants));

Converting and Passing in an Array of Numbers Using MongoDB `$in` Operator

In my MongoDB/Node backend I am taking in passed-in parameters and then filtering on some data.
The first thing I do is take in string values (that happen to represent numbers) such as "1", "2", etc. and turn them into a comma-separated array.
Now I need to filter on a property called "responsibilitySequence". The thing is, the values for this property are of type "number", not "string".
So how do I adjust the following function so that what gets passed-in as an array that Mongo will evaluate using the $in operator, consists of numbers, not string values?
if (responsibilitySequence) {
let arrResponsibilitySequence = [];
arrResponsibilitySequence = responsibilitySequence.split(",");
_.each(arrResponsibilitySequence, (l, key, c) => {
arrResponsibilitySequence[key] = new RegExp(arrResponsibilitySequence[key], "i");
});
search.responsibilitySequence = {
$in: arrResponsibilitySequence
};
}
You could just map the values and parse them as int:
if (responsibilitySequence) {
let arrResponsibilitySequence = responsibilitySequence.split(",");
search.responsibilitySequence = {
$in: arrResponsibilitySequence.map(x => Number.parseInt(x)) // or just +x
};
}

transform json object to an array field

I want to transform a list of objects with object having this form
{
"idActivite": 1,
"nomActivite": "Accueil des participants autour d’un café viennoiseries",
"descriptionActivite": "",
"lieuActivite": "",
"typeActivite": "",
"horaireDebActivite": 1512028800,
"horaireFinActivite": 1512059388,
"horaireDebSession": 1512030600,
"horaireFinSession": 1512318588,
"nomSession": "",
"isInSession": false
}
to a one like this :
[
"idActivite": 1,
"nomActivite": "Accueil des participants autour d’un café viennoiseries",
"descriptionActivite": "",
"lieuActivite": "",
"typeActivite": "",
"horaireDebActivite": 1512028800,
"horaireFinActivite": 1512059388,
"horaireDebSession": 1512030600,
"horaireFinSession": 1512318588,
"nomSession": "",
"isInSession": false
]
using type script 2.5
Both are theoretically still objects and that isnt the right way to go about it! An array is simply a list of elements with a number index, the example you are giving uses a string to index and thus is still according to the JSON spec an object. If the issue you are having is to iterate through it use this:
for(var key in array){
console.log(array[key]);
}
Assuming you want an array like [ {key, value} ]
let x = { a: 1, b: 2 }
let y = []
// Note the 'in' keyword instead of 'of'
for (const key in x) {
y.push({ key: key, value: x[key] })
}
// Will print [ { key: 'a', value: 1 }, { key: 'b', value: 2 } ]
console.log(y)
Note that this solution scales linearly with the size of the array.

Resources