How to use an object to delete it from objects array javascript? - javascript

I have an array of objects and I want to check whether a given object is present in the array and if yes,I want to delete that,If not I have to add it to the array.
I am doing this:
var arr=[
{
name: "Jack",
type: "Jill",
},
{
name: "Heer",
type: "Ranjha",
},
{
name: "laila",
type: "Majnu",
};
]
var tosearch = {
name: "Jack",
type: "Jill",
};
if(arr.includes(tosearch))
{
//I want to delete it from the arr.
}
else
arr.push(tosearch)
How can I achieve the above implementation?
Thanks

You can use this code
arr = arr.filter(item => item !== tosearch)
but, there is better way for handle this you can add an id field for each object and wherever you want to check and find specific item you can use that id
arr = arr.filter(item => item.id !== tosearch.id)

Deleting an element from an array using filter. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
const newArray = existingArray.filter(element => element.id != deleteId);
Searching I usually use a simple findIndex. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
const doesElementExist = arr.findIndex(element => element.id === selectedId);
if (doesElementExist > 0) { // Delete element }
This relies on you having a unique identifier in the object potentially the name? I am not sure what your data will be.

Issue
Array.prototype.includes only works for primitives and object via shallow reference equality, i.e. if they are the same object in memory.
Solution
Create a utility to check if the array contains some element where every property of the "search" object is equal.
const arrayContainsObject = (array, object) =>
array.findIndex((el) =>
Object.entries(object).every(([key, value]) => el[key] === value)
);
This example returns the index of the element if found, otherwise it returns -1.
You can use this to either filter the element from the array or append it.
let result;
const index = arrayContainsObject(arr, toSearch);
if (index !== -1) {
result = arr.filter((el, i) => i !== index);
} else {
result = arr.concat(toSearch);
}
const arr = [
{
name: "Jack",
type: "Jill"
},
{
name: "Heer",
type: "Ranjha"
},
{
name: "laila",
type: "Majnu"
}
];
const toSearch = {
name: "Jack",
type: "Jill"
};
const arrayContainsObject = (array, object) =>
array.findIndex((el) =>
Object.entries(object).every(([key, value]) => el[key] === value)
);
let result;
const index = arrayContainsObject(arr, toSearch);
if (index !== -1) {
result = arr.filter((el, i) => i !== index);
} else {
result = arr.concat(toSearch);
}
console.log(result);

You can use Array.prototype.filter to achieve filtering:
/** utils.js */
// default options can be set, here we will create search filter which pick from id
const defaultSearchFilterOptions = { key: 'id', pick: true }
/**
* #description
* factory to create array filter utilities
* #params {object} [options={}] - options used to generate the new filter
* #params {string} [options.key='id'] - key used for comparing
* #params {boolean} [options.pick=true] - inverse the filter (with/without)
* #params {string} options.search - exact match to search (can be improved with a regex or whatever etc..
* #returns {function} filter - function that can be used with `Array.prototype.filter`
*/
function createSearchFilter(options = {}) {
// apply user's options on top of default options, user MUST pass at least "search" options
const { key, search, pick } = { ...defaultSearchFilterOptions, ...options }
// return a filter function, based on computed options
return (item) => pick ? item[key] === search : item[key] !== search
}
/** app.js */
// data
var arr = [
{
name: "Jack",
type: "Jill",
},
{
name: "Heer",
type: "Ranjha",
},
{
name: "laila",
type: "Majnu",
}
];
// using factory, create a filter on name where value is "jack"
const filterInJack = createSearchFilter({
key: 'name',
search: 'Jack',
});
// using factory, create a filter on name where value is not "jack"
const filterOutJack = createSearchFilter({
key: 'name',
search: 'Jack',
pick: false,
});
/** Results */
console.log(arr.filter(filterInJack));
console.log(arr.filter(filterOutJack));
Source: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

If the number of properties are fixed(in your case its 2 name and type) and you know them before running then you can simply use this.
This approach may not be an ideal one but if the data is of this type then i guess this might be might be a good and easy to understand approach
//here i is the index of a object in arr
if(arr[i].name == tosearch.name && arr[i].type == tosearch.type) {
//delete it
} else {
arr.push(tosearch);
}

Related

Merging values from an array of strings into a nested object in javascript

I want to merge values from an array into a static nested object. The array containing the values is something like this,
['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27']
and the object in which the values has to be merged is,
const person = {
details_1: {
name: null,
hobbies: null,
profession: null
},
details_2: {
age: null
}
};
I want my output object to look like below,
const updated_person = {
details_1: {
name: 'ABC XYZ',
hobbies: [M,N,O,P],
profession: 'S'
},
details_2: {
age: 27
}
};
Thanks a lot for your help!
I made another solution with a different approach.
Here I used an interface weher I described the desired data structure.
In the second part the string array is tranformed into key and value pairs. Thereform are filtered the keys of interface and added into an empty object literal.
const data = ["name=ABC XYZ", "hobbies=[M,N,O,P]", "profession=S", "age=27"];
const dataInterface = {
details_1: { name: null, hobbies: null, profession: null },
details_2: { age: null },
};
function orederData(arr) {
const record = arr.map((item) => {
let [key, value] = item.split("=");
if (value[0] === "[" && value[value.length - 1] === "]") {
value = value.slice(1, value.length - 1).split(",");
}
return { key, value };
});
const dataBlock = {};
Object.keys(dataInterface).map((detail) => {
dataBlock[detail] = {};
Object.keys(dataInterface[detail]).forEach((dataKey) => {
dataBlock[detail][dataKey] = record.filter((record) => {
return record.key === dataKey;
})[0].value;
});
});
return dataBlock;
}
const orderedData = orederData(data);
console.log(orderedData);
You can simply achieve this by iterating the input array.
const arr = ['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27'];
const person = {
details_1: {},
details_2: {}
};
arr.forEach(item => {
(item.split('=')[0] !== 'age') ? person.details_1[item.split('=')[0]] = item.split('=')[1] : person.details_2[item.split('=')[0]] = item.split('=')[1]
});
console.log(person);
There is no way to cleanly merge an unstructured array into a structured object such that the array values end up in the appropriately keyed person properties.
javascript does provide the assign() function that merges objects but for YOUR requirements your source data needs to be an object similarly structured and not an array.
so this:
['name=ABC XYZ', 'hobbies=[M,N,O,P]', 'profession=S', 'age=27']
would need to become this:
const source= [{details_1: {"name":"ABC XYZ", "hobbies":"[M,N,O,P]", "profession":"S"}, details_2: {"age":"27"}}]
such that a call to Object.assign():
const new_person = Object.assign(person, source[0]);
fills this
const person = {
details_1: {
name: null,
hobbies: null,
profession: null
},
details_2: {
age: null
}
};
properly, though you may need to clone or instantiate and empty person first.
or, if person is an Object you could have a fill() method that knows what to do with the array data.

How to add a property to a dynamically changing object from an API?

I hope someone can help me with my problem! I didn't find the right thing through the search and maybe someone can give me a hint.
I am calling an API that returns an object that in turn contains nested objects. In these nested objects there are two properties "value" and "scale". I want to divide these two properties and write them as properties in the same object.
The data I get from the API is dynamic, which means it is constantly changing.
Example:
// call api
const apiCall = callApi(...);
// return object
console.log(apiCall);
{
id: '3454353458764389759834534534',
json_data: {
persons: {
de: {
name: 'Bob',
data: {
scale: 100,
value: 2459,
},
},
be: {
name: 'Alice',
data: {
scale: 10000,
value: 1459,
},
},
},
url: 'https://stackoverflow.com/',
timestamp: '2021-10-23T12:00:11+00:00',
disclaimer: 'Some bla bla',
},
}
// targed object
const objTarged = {
id: '3454353458764389759834534534',
json_data: {
persons: {
de: {
name: 'Bob',
data: {
scale: 100,
value: 2459,
result: 24.59 // value / scale = result
},
},
be: {
name: 'Alice',
data: {
scale: 10000,
value: 1459,
result: 0.1459 // value / scale = result
},
},
},
url: 'https://stackoverflow.com/',
timestamp: '2021-10-23T12:00:11+00:00',
disclaimer: 'Some bla bla',
},
};
My thoughts:
do I need to map the object into a new object?
how can I do this if the source object is constantly changing (Object.values?)
How can I write the result of Value / Scale as a new property in the same object each time I call the API?
Big thanks in advance :)
It might be helpful to decompose the problem into first finding the nested objects with the keys you're interested in. Having done that, it will be easy to augment those objects with the desired calculation.
Below is a sort of generic function that finds a nested object based on it having a particular key. With that, fixMyApiData writes itself...
// return an array of objects that are nested in the passed object which contain the passed key
function objectsContainingKey(object, key) {
let results = [];
Object.keys(object).forEach(k => {
if (k === key) results.push(object);
if (object[k] && typeof object[k] === 'object')
results = results.concat(objectsContainingKey(object[k], key));
});
return results;
}
// find the nested objects we care about and augment them with the value/scale calculation
function fixMyApiData(apiData) {
objectsContainingKey(apiData, 'scale').forEach(data => {
if (data.value) data.result = data.value / data.scale;
})
}
let apiData = {
id: '3454353458764389759834534534',
json_data: {
persons: {
de: {
name: 'Bob',
data: {
scale: 100,
value: 2459,
},
},
be: {
name: 'Alice',
data: {
scale: 10000,
value: 1459,
},
},
},
url: 'https://stackoverflow.com/',
timestamp: '2021-10-23T12:00:11+00:00',
disclaimer: 'Some bla bla',
},
};
fixMyApiData(apiData);
console.log(apiData);
I would create a mapValues() function that takes an object, and creates a new object by passing each of the object's values in a transforming function.
Whenever the api call returns a new object, we recreate the new object with the result property according to the structure.
How does the mapValues function works?
Whenever an object (or array) is passed to mapValues, it's converted to an array of [key, value] pairs. The pairs are then mapped to new [key, pair] entries by applying transformFn to the value. The transform array of pairs is then converted back to an using Object.fromEntries().
const mapValues = (transformFn, obj) => Object.fromEntries(
Object.entries(obj)
.map(([key, value]) => [key, transformFn(value)])
)
const apiCall = {"persons":{"de":{"name":"Bob","scale":100,"value":2459},"be":{"name":"Alice","scale":10000,"value":1459}}}
const result = mapValues(
val => mapValues(v => ({
...v,
result: v.value / v.scale,
}), val),
apiCall
)
console.log(result)
If you have multiple nested levels with properties you don't want to transform, we can also pass the key to the transformFn for a more granular change. Now we can create a recursive function to traverse the tree, and only update objects which have a specific key.
const mapValues = (transformFn, obj) => Object.fromEntries(
Object.entries(obj)
.map(([key, value]) => [key, transformFn(value, key)])
)
const fn = obj => mapValues(
(val, key) => {
// if the key is data create a new object with a result property
if(key === 'data') return ({
...val,
result: val.value / val.scale,
})
// if it's object pass it to the recursive function
if(typeof val === 'object') return fn(val)
return val
},
obj
)
const apiCall = {"id":"3454353458764389759834534534","json_data":{"persons":{"de":{"name":"Bob","data":{"scale":100,"value":2459}},"be":{"name":"Alice","data":{"scale":10000,"value":1459}}},"url":"https://stackoverflow.com/","timestamp":"2021-10-23T12:00:11+00:00","disclaimer":"Some bla bla"}}
const result = fn(apiCall)
console.log(result)

i wanna return correctly children's object. how can i?

function Ha8(arr, id) {
let result = [];
for(let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i].children)) {
// if it is a array, it going to be run recursive
result.push(arr[i].children)
const col = Ha8(result[i], id);
if(col === id) {
// find it in array in array
return result
// then return the id object,
} else {
continue; // still can't find.. go ahead!
}
} else if (arr[i]['id']===id) {
return arr[i] // will return valid id object
}
return null // if its none , return null, or parameter id is undefined.
}
}
I m write Intended direction. but its not work..
how can i fix ? give me some tip please.
let input = [
{
id: 1,
name: 'johnny',
},
{
id: 2,
name: 'ingi',
children: [
{
id: 3,
name: 'johnson',
},
{
id: 5,
name: 'steve',
children: [
{
id: 6,
name: 'lisa',
},
],
},
{
id: 11,
},
],
},
{
id: '13',
},
];
output = Ha8(input, 5);
console.log(output); // --> { id: 5, name: 'steve', children: [{ id: 6, name: 'lisa' }] }
output = Ha8(input, 99);
console.log(output); // --> null
I wanna return like that, but only return 'null' ..
need to check children's id and return children's object by using recursive.
so i write like that. but i have no idea..
how to return correctly children id's element?
I will give you an answer using a totally different approach, and using the magic of the JSON.stringify() method, more specifically the replacer optional parameter, which allows the use of a callback function that can be used as a filter.
As you can see, it simplifies a lot the final code. It could also be modified to introduce not only an id, but also any key or value, as I did in my final approach.
EDIT: Following your suggestion, as you prefer your function to be recursive, I recommend you to use the Array.reduce() method. It allows an elegant iteration through all the properties until the needs are met.
Using null as initial value, which is the last argument of the reduce method, it allows to iterate through all fields in the array in the following way:
The first if will always be skipped on the first iteration, as the initial value is null.
The second if will set the currentValue to the accumulator if the property id exists and is equal to the value you are trying to find
The third if, which you could add an Array.isArray() to add a type validation, will check if the property children exists. As it is the last one, it will only work if all the other conditions aren't met. If this property exists, it will call again Ha8Recursive in order to start again the process.
Finally, if neither of this works, it should return null. The absence of this last condition would return undefined if the input id doesn't exist
const Ha8 = (array, inputKey, inputValue) => {
let children = null;
JSON.stringify(array, (key, value) => {
if (value[inputKey] && value[inputKey] === inputValue) {
children = value;
}
return value;
});
return children;
};
const Ha8Recursive = (array, inputKey, inputValue) => {
return array.reduce((accumulator, currentValue) => {
if (accumulator) {
return accumulator;
} else if (currentValue[inputKey] && currentValue[inputKey] === inputValue) {
return currentValue;
} else if (currentValue.children) {
return Ha8Recursive(currentValue.children, inputKey, inputValue);
} else {
return null;
}
}, null)
}
const input = [{"id":1,"name":"johnny"},{"id":2,"name":"ingi","children":[{"id":3,"name":"johnson"},{"id":5,"name":"steve","children":[{"id":6,"name":"lisa"}]},{"id":11}]},{"id":"13"}];
console.log('JSON stringify function');
console.log(Ha8(input, 'id', 5));
console.log('Recursive function')
console.log(Ha8Recursive(input, 'id', 5));

Removing duplicates with in an object array using angular 4

I have an array with below list of items as shown in image , I would like to remove the duplicates
[L7-LO, %L7-LO] from that array.
I have tried with the following conditions:
Scenario 1 :
this.formulalist.filter((el, i, a) => i == a.indexOf(el))
Scenario 2:
Observable.merge(this.formulalist).distinct((x) => x.Value)
.subscribe(y => {
this.formulalist.push(y)
});
Scenario 3:
this.formulalist.forEach((item, index) => {
if (index !== this.formulalist.findIndex(i => i.Value == item.Value))
{
this.formulalist.splice(index, 1);
}
});
None of the three scenarios above were able to remove the duplicates from that array. Could any one please help on this query?
angular is not necessary use vanillajs
filter the elements with only one occurrence and add to the new list the first occurrence
let newFormulalist = formulalist.filter((v,i) => formulalist.findIndex(item => item.value == v.value) === i);
Try populating a new array without duplicates. Assign the new array later to formulalist.
newArr = []
this.formulalist.forEach((item, index) => {
if (this.newArr.findIndex(i => i.Value == item.Value) === -1)
{
this.newArr.push(item)
}
});
this.formulalist = this.newArr
EDIT
Looking at the answer above, the solution seems so outdated. A better approach would have been to use an Array.filter() than a Array.forEach().
But, having a better solution would be nice, now when I see this question, I feel findIndex() not to be a good approach because of the extra traversal.
I may have a Set and store the values in the Set on which I want to filter, If the Set has those entries, I would skip those elements from the array.
Or a nicer approach is the one that is used by Akitha_MJ, very concise. One loop for the array length, an Object(Map) in the loop with keys being the value on which we want to remove duplicates and the values being the full Object(Array element) itself. On the repetition of the element in the loop, the element would be simply replaced in the Map. Later just take out the values from the Map.
const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());
Hope this works !!
// user reduce method to remove duplicates from object array , very easily
this.formulalist= this.formulalist.reduce((a, b) => {
if (!a.find(data => data.name === b.name)) {
a.push(b);
}
return a;
}, []);
// o/p = in formulalist you will find only unique values
Use a reducer returning a new array of the unique objects:
const input = [{
value: 'L7-LO',
name: 'L7-LO'
},
{
value: '%L7-LO',
name: '%L7-LO'
},
{
value: 'L7-LO',
name: 'L7-LO'
},
{
value: '%L7-LO',
name: '%L7-LO'
},
{
value: 'L7-L3',
name: 'L7-L3'
},
{
value: '%L7-L3',
name: '%L7-L3'
},
{
value: 'LO-L3',
name: 'LO-L3'
},
{
value: '%LO-L3',
name: '%LO-L3'
}
];
console.log(input.reduce((acc, val) => {
if (!acc.find(el => el.value === val.value)) {
acc.push(val);
}
return acc;
}, []));
if you are working using ES6 and up, basic JS using map and filter functions makes it easy.
var array = [{value:"a"},{value:"b"},{value:"c"},{value:"a"},{value:"c"},{value:"d"}];
console.log(array.filter((obj, pos, arr) => {
return arr.map(mapObj => mapObj["value"]).indexOf(obj["value"]) === pos;
}));
Filtering for unique values is much faster with assigning values to some object properties - there not will be duplicates.
This approach gets better and better with every +1 member of initial array, because looping will be causing fast algorithm complications
let arr = [
{value: 'L7-LO', name: 'L7-LO'},
{value: '%L7-LO', name: '%L7-LO'},
{value: 'L7-LO', name: 'L7-LO'},
{value: '%L7-LO', name: '%L7-LO'},
{value: 'L7-L3', name: 'L7-L3'},
{value: '%L7-L3', name: '%L7-L3'},
{value: 'LO-L3', name: 'LO-L3'},
{value: '%LO-L3', name: '%LO-L3'}
];
let obj = {};
const unique = () => {
let result = [];
arr.forEach((item, i) => {
obj[item['value']] = i;
});
for (let key in obj) {
let index = obj[key];
result.push(arr[index])
}
return result;
}
arr = unique(); // for example;
console.log(arr);

JavaScript - Filter object based on multiple values

I need to filter some data based on multiple values. Language, title and slug
[
{
de: "4567uy55",
en: "654321",
lang: [
{
id: "654321",
language: "English",
title: "Title1"
},
{
id: "4567uy55",
language: "German",
title: "Title2"
}
],
slug: 'some-slug'
},
...
]
What I have now returns all objects which have one or part of the filters(in case title is This is a title, the word this should match), but I need to return objects which have all of them.
I used an object flattner just to get all properties and values in one object, but I can't get it to filter the way I need it.
multiFilter = (arr, filters) => {
console.log(filters)
console.log(arr)
let newArray = []
for (let c of arr) {
let flatCourse = flatten(c)
for (let k in flatCourse) {
const keyArr = k.split('/')
const filterKeys = Object.keys(filters)
Object.keys(filters).map((key) => {
if (keyArr.includes(key)) {
const flatVal = flatCourse[k].toString().toLowerCase()
const filterVal = filters[key].toString().toLowerCase()
console.log(flatVal)
console.log(filterVal)
if (flatVal.includes(filterVal)) {
arr = []
arr.push(c)
newArray.push(c)
}
}
})
}
}
return newArray
}
Filters look like this:
[
language:["English"],
title: ["Some title"],
slug:["some slug"]
]
Instead of mixing for loops and functional chaining you could just go with one of them:
multiFilter = (arr, filters) =>
arr.map(flatten).filter(el => // filter out elements from arr
Object.entries(filters).every(([fKey, fValues]) => // ensure that every key is included in the object
Object.entries(el).some(([oKey, oValue]) =>
oKey.split("/").includes(fKey) && fValues.includes(oValue)// make sure that at least one of the values equals the elements value
)
)
);
arr.filter(course => {
// Returns an array of booleans corresponding to whether or not each filter condition is satisfied
return Object.keys(filters).map(key => {
return filters[key].map(filter => {
// Special case here because lang is an array
if (key == 'language' && course.lang != undefined) {
return course.lang.some(lang => lang[key].includes(filter))
}
if (course[key] == undefined) {
return false
}
return course[key].includes(filter)
}).every(result => result == true)
}).every(result => result == true)
})

Categories

Resources