Remove empty object from array of objects - javascript

I have an array of objects and a delete function that pass the index as a parameter but fails to remove the empty object. Objects containing properties can be removed. Does anyone know how to fix it? The example code is shown below.
let array = [
{
id: '1',
name: 'sam',
dateOfBirth: '1998-01-01'
},
{
id: '2',
name: 'chris',
dateOfBirth: '1970-01-01'
},
{
id: '3',
name: 'daisy',
dateOfBirth: '2000-01-01'
},
{}
]
// Objects contain properties can be removed but empty object can not be removed.
const deleteItem = (index) => {
return array.splice(index, 1);
};

Use Array.filter to filter out the items which have no properties
let array = [
{id:"1",name:"sam",dateOfBirth:"1998-01-01"},
{id:"2",name:"chris",dateOfBirth:"1970-01-01"},
{id:"3",name:"daisy",dateOfBirth:"2000-01-01"},
{}
]
const filtered = array.filter(e => Object.keys(e).length)
console.log(filtered)
The above works since Object.keys will return an array of the properties of the object. Getting its length property will get the number of items in the array. If the length property is 0, it is coerced to false (see: Falsy values).

Related

JavaScript Replacing Object in Array with ID Number

So I have a series of objects that are pulled from an API and inputted into an array, something like such:
array = [
{id: 0, name: "First", relationship: "Friend"},
{id: 1, name: "Second", relationship: "Friend"}
]
The user is allowed to add and remove objects to the list freely (they will appear within a Vue.JS DataTable), and said user is allowed a maximum of 4 objects within the array (lets say 4 "friends")
How should I go about implementing a function that searches the existing array (say, if its populated from the API), and inputs the new object with the corresponding ID that is missing (so if the user deletes the object with the id 2, and adds another, it will search said array with objects, find the missing id 2 slot in the array, and input the object in its place)?
Previously I have gone about it via implement array.find() with conditionals to see if the array contains or does not contain the certain id value, however, it searches through each entry and can end up inserting the same object multiple times. Another method I haven't attempted yet would be having a separate map that contains ids, and then when a user removes an object, having it correspond with the map, and vice versa when adding.
Any suggestions? Thanks
Instead of an array, I'd keep an object in data. Have it keyed by id, like this:
let objects = {
0: { id: 0, name: 'name0', relationship: 'relationship0' },
1: { id: 1, name: 'name1', relationship: 'relationship1' },
}
Integer keys in modern JS will preserve insertion order, so you can think of this object as ordered. The API probably returns an array, so do this...
// in the method that fetches from the api
let arrayFromApi = [...];
this.objects = array.reduce((acc, obj) => {
acc[obj.id] = obj; // insertion order will be preserved
return acc;
}, {});
Your UI probably wants an array, so do this (refer to "array" in the markup):
computed: {
array() {
return Object.values(this.objects);
},
To create a new object, insert it in order, minding the available keys. Note this is a linear search, but with small numbers of objects this will be plenty fast
methods: {
// assumes maxId is const like 4 (or 40, but maybe not 400)
createObject(name, relationship) {
let object = { name, relationship };
for (let i=0; i< maxId; i++) {
if (!this.objects[i]) {
object.id = i;
this.objects[i] = object;
break;
}
}
try this,
let array = [
{id: 0, name: "First", relationship: "Friend"},
{id: 4, name: "Second", relationship: "Friend"},
{id: 2, name: "Second", relationship: "Friend"},
]
const addItem = (item) => {
let prevId = -1
// this is unnecessary if your array is already sorted by id.
// in this example array ids are not sorted. e.g. 0, 4, 2
array.sort((a, b) => a.id - b.id)
//
array.forEach(ob => {
if(ob.id === prevId + 1) prevId++
else return;
})
item = {...item, id: prevId + 1 }
array.splice(prevId+1, 0, item)
}
addItem({name: "x", relationship: "y"})
addItem({name: "a", relationship: "b"})
addItem({name: "c", relationship: "d"})
console.log(array)
You can simply achieve this with the help of Array.find() method along with the Array.indexOf() and Array.splice().
Live Demo :
// Input array of objects (coming from API) and suppose user deleted 2nd id object from the array.
const arr = [
{id: 0, name: "First", relationship: "Friend" },
{id: 1, name: "Second", relationship: "Friend" },
{id: 3, name: "Fourth", relationship: "Friend" }
];
// find the objects next to missing object.
const res = arr.find((obj, index) => obj.id !== index);
// find the index where we have to input the new object.
const index = arr.indexOf(res);
// New object user want to insert
const newObj = {
id: index,
name: "Third",
relationship: "Friend"
}
// Insert the new object into an array at the missing position.
arr.splice(index, 0, newObj);
// Output
console.log(arr);

How to filter few properties of an object which is in Array of objects if one property equals property from another object

I have a object which has some properties for one user, and I have array of objects which is returned from API.
My goal is to check which object of Array of objects has the same property as the one single initial object, and then it should return only part of it's properities.
I have tried to use .map on Array of objects but it seems not workig.
Below is the code example. I have also prepared codesandbox if You wish.
const user =
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
car: "audi"
}
;
const usersAnimal = [
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
animal: "cat",
animalSize: "small",
animalName: "Bat"
},
{
name: "john",
lastName: "smith",
fullName: "john smith",
animal: "dog",
animalSize: "middle",
animalName: "Jerry"
},
{
name: "Anna",
lastName: "Nilsson",
fullName: "Anna Nilsson",
animal: "cow",
animalSize: "big",
animalName: "Dorrie"
}
];
const filtered = usersAnimal.map((userAnimal)=>userAnimal.fullName === user.fullName && return userAnimal.animalName & userAnimal.animalSize & userAnimal.animal);
thanks
https://codesandbox.io/s/admiring-edison-qxff42?file=/src/App.js
For case like this, it would be far easier if you filter it out first then proceed using map:
const filtered = usersAnimal
.filter((animal) => animal.fullName === user.fullName)
.map(({ animalName, animalSize, animal }) => {
return {
animalName,
animalSize,
animal
};
});
I am providing a for loop solution as I haven't learnt many array methods in javascript.
For me the simplest option is to use a for loop and an if check to loop through the arrays values to check for included values.
for (let v in usersAnimal) {
if (usersAnimal[v].fullName === user.fullName) {
console.log(usersAnimal[v])
}
}
The code above will log the entire usersAnimal object containing the fullname we are looking for.
{
name: 'jan',
lastName: 'kowalski',
fullName: 'jan kowalski',
animal: 'cat',
animalSize: 'small',
animalName: 'Bat'
}
commented for further understanding
for (let v in usersAnimal) {
//loops though the array
if (usersAnimal[v].fullName === user.fullName) {
//when the index value 'v' has a fullname that matches the user fullname value
// it passes the if check and logs that object value
return console.log(usersAnimal[v])
//return true...
}
//return null
}
//etc
If you want to filter, I recommend you to use filter.
The map method will create a new array, the content of which is the set of results returned by each element of the original array after the callback function is operated
const user = {name:"jan",lastName:"kowalski",fullName:"jan kowalski",car:"audi"};
const usersAnimal = [{name:"jan",lastName:"kowalski",fullName:"jan kowalski",animal:"cat",animalSize:"small",animalName:"Bat"},{name:"john",lastName:"smith",fullName:"john smith",animal:"dog",animalSize:"middle",animalName:"Jerry"}];
// Get an array of matching objects
let filtered =
usersAnimal.filter(o => o.fullName === user.fullName);
// You get the filtered array, then you can get the required properties
filtered.forEach(o => {
console.log(
'animal:%s, animalSize:%s, animalName:%s',
o?.animal, o?.animalSize, o?.animalName
);
});
// Then use map to process each element
filtered = filtered.map(o => {
const {animal, animalSize, animalName} = o;
return {animal, animalSize, animalName};
});
console.log('filtered', filtered);

I have array with objects, I need to fetch all the objects that matches the value of userId starts with 'US' [duplicate]

This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed last year.
Below is the array with objects:
myArray:[
{"name":"Ram", "email":"ram#gmail.com", "userId":"HB000006"},
{"name":"Shyam", "email":"shyam23#gmail.com", "userId":"US000026"},
{"name":"John", "email":"john#gmail.com", "userId":"HB000011"},
{"name":"Bob", "email":"bob32#gmail.com", "userId":"US000106"}
]}
I tried this but I am not getting output:
item= myArray.filter(element => element.includes("US"));
I am new to Angular.
let filteredArray = myArray.filter(function (item){
return item.userId.substring(0,2).includes('US')
})
Console.log(filteredArray)
//Output
[ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' },
{ name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
As noted by #halfer - You need to filter on the property that you are interested in - in this case - 'userId' - you can do this by simply adding the property into the code you already had tried and it will log out the specified items - or alternatively - you can make a utility function that takes the array, property and target string as arguments and this will allo2w you to search / filter other arrays and by any property and target string .
These two options are shown below and both log out the same results.
const myArray = [
{"name":"Ram", "email":"ram#gmail.com", "userId":"HB000006"},
{"name":"Shyam", "email":"shyam23#gmail.com", "userId":"US000026"},
{"name":"John", "email":"john#gmail.com", "userId":"HB000011"},
{"name":"Bob", "email":"bob32#gmail.com", "userId":"US000106"}
]
// option 1 - direct filtering
const matchingItems = myArray.filter(element => element.userId.includes("US"));
console.log(matchingItems);
// gives - [ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]
//option 2 - create a function that takes arguments and returns the matches
const matches = (arr, prop, str) => {
return arr.filter(element => element[prop].includes(str));
}
console.log(matches(myArray, 'userId', 'US'));
// gives - [ { name: 'Shyam', email: 'shyam23#gmail.com', userId: 'US000026' }, { name: 'Bob', email: 'bob32#gmail.com', userId: 'US000106' } ]

Spread syntax in an array of objects

I have a question regarding the spread syntax and an array of objects.
Having an array of objects like:
const array = [{age:50}, {age:27}]
According to this answer: https://stackoverflow.com/a/54138394/6781511, using the spread syntax will result in referencedArray having a shallow copy of array.
const referencedArray = [...array]
What then is the difference between using the spread syntax and not using it?
const referencedArray = [...array]
vs
const referencedArray = array
See the following example.
When you make a shallow copy, assigning to an element of the original doesn't affect the clone. When you don't make a copy, assigning to the original affects the other reference.
Since it's a shallow copy, assigning to properties of the objects in the array affects all of them. Only the array was copied by spreading, not the objects.
const array = [{age:50}, {age:27}];
const clonedArray = [...array];
const notClonedArray = array;
array[0] = {age: 100};
array[1].age = 30;
console.log("Original:", array);
console.log("Cloned:", clonedArray);
console.log("Not cloned:", notClonedArray);
The objects within the arrays have the same reference in both, but in the spread scenario, modifying the array will not affect the original.
const array = [{ name: 'Joe' }, { name: 'Paul' }];
const spreadArray = [...array];
const cloneArray = array;
spreadArray[3] = { name: 'Bob' };
console.log(array); // [{ name: 'Joe' }, { name: 'Paul' }];
cloneArray[3] = { name: 'Bob' };
console.log(array); // [{ name: 'Joe' }, { name: 'Paul' }, { name: 'Bob'} ];
That's because cloneArray is assigned by reference to array, while spreadArray is assigned to a new array with the same elements as array. That's also why
cloneArray === array; // true
spreadArray === array; // false

Getting a property of an object within an array

I use Vue.js and have a method that compares a value from one array with a value from another array.
array1: [{ name: 'test1', somevar: true }, { name: 'test2', somevar: false }]
array2: ['test1', 'test3']
compare() {
//I want to access an object property within an array1
this.array1.forEach((element) => {
if(this.array1.element.name.includes(this.array2[0])) {
// if it is true, I would like to remove that compared value from an array 1
if(this.array2[0] !== -1) {
var index = this.array1.element.name.indexOf(this.array2[0])
this.array1.splice(index, 1)
}
}
I think this part: this.array1.forEach((element) is incorrect. How can I access property of that object?
array1 is an array, not an object, so accessing this.array1.element won't work. Simply refrence the element as the parmeter given to forEach instead.
Also, the function passed forEach accepts another argument: the second argument represents the current element's index, so there's no need to search for indexOf.
But, even better than those tweaks, it would be more appropriate to use filter in this situation:
const obj = {
array1: [{ name: 'test1', somevar: true }, { name: 'test2', somevar: false }],
array2: ['test1', 'test3'],
compare() {
obj.array1 = obj.array1.filter(({ name }) => (
!obj.array2.includes(name)
))
}
}
obj.compare();
console.log(obj.array1);

Categories