How to delete new array in react native object - arrays

I have following array
[{
"games1": [{
"playername": "1"
}]
},
{
"games2": [{
"playername": "1"
},
{
"playername": "2"
}
]
}
]
I want to delete games2 from the array how to do this
I want this type of output
[{
"games1": [{
"playername": "1"
}]
}
}]

Use filter to filter what you want to keep.
Like this:
const arr = [
{
games1: [
{
playername: '1',
},
],
},
{
games2: [
{
playername: '1',
},
{
playername: '2',
},
],
},
]
// keep games1
const newArr = arr.filter((r) => r.games1)
console.log(newArr)
// remove games2, keep others
const newArr2 = arr.filter((r) => !r.games2)
console.log(newArr2)
output would be
[
{
"games1": [
{
"playername": "1"
}
]
}
]

const NewArray = array.filter((item) => item !== "games2");
console.log(NewArray)

Try the below code:
let final = x.filter(x=>{
let c = Object.getOwnPropertyNames(x)
return c!="games2"
})
here the output of the 'final' is :
[{
"games1": [{
"playername": "1"
}]
}
}]

Related

How to update nested array of objects in ReactJS

I have an array of object like this:
const tempobj = [
{
id: "1",
fanimate: [
{
id: "111",
animate: "xyz",
},
],
},];
Now I want to add more animations inside this array, such that each object gets added in the fanimate such that:
const tempobj = [
{
id: "1",
fanimate: [
{
id: "111",
animate: "xyz",
},
{
id: "222",
animate: "def",
},
],
},];
I tried using the hook useState, but I am getting undefined results
const tempobj = [
{
id: "1",
fanimate: [
{
id: "111",
animate: "xyz",
},
],
}];
const modified = tempobj.map(temp => {
const newtemp = {
id: temp.id,
fanimate: [...temp.fanimate, {id:"222", animate:"def"}]
}
return newtemp;
})
console.log(modified);
You could just spread all the places
const tempObj = {
id:'1',
fan:[
{
id:'2',
animate:'xyz'
}
]
}
console.log(tempObj)
const newtest={...testObj,fan:[...testObj.fan, {id:'3', animate:'tuz'}]}
console.log(newtest)
Try this:
const tempobj = [
{
id: "1",
fanimate: [
{
id: "111",
animate: "xyz"
}
]
}
];
const [state, setState] = useState(tempobj);
function updateArray(newItem) {
setState(
state.map((item) => ({ ...item, fanimate: [...item.fanimate, newItem] }))
);
}
You can push the newItem to the original fanimate array using spread operator, everytime a new item is added, the original array data is copied by ...item.fanimate:
{ ...item, fanimate: [...item.fanimate, newItem] }
BTW the naming of tempobj really should be tempArr or tempArray.
A working sandbox

Mongoose In ArrayElemAt Issue In Aggregate

temporaryshifts is equal to
[{_id:123,
arr:[{_id:123321,name:"Bluh Bluh",date:"bluh bluh"}]
}]
so i want to access temporaryshifts[0].arr[0]
but i dont know how to access
$project:{
shiftArr:{$arrayElemAt:['$temporaryshifts',0]}
}
You have to make use of the let operators to make use of two $arrayElemAt Operators.
db.collection.aggregate([
{
"$project": {
"temporaryshifts": {
"$let": {
"vars": {
"masterKey": {
"$arrayElemAt": [
"$temporaryshifts",
0
]
}
},
"in": {
"$arrayElemAt": [
"$$masterKey.arr",
0
]
}
},
}
},
},
])
Mongo Playground Sample Execution
To Understand Properly i Am taking this example and suppose that this our data
`
[
{
_id: 123,
arr: [
{
_id: 123321,
name: "Bluh Bluh",
date: "bluh bluh"
},
{
_id: 1233219,
name: "Bluh Bluh2",
date: "bluh bluh2"
}
]
},
{
_id: 1234,
arr: [
{
_id: 1233214,
name: "Bluh Bluh4",
date: "bluh bluh4"
}
]
},
]
`
Can get temporaryshifts[0].arr[0] with this query
db.collection.aggregate([
{
"$match": {
"_id": 123
}
},
{
"$project": {
shiftArr: {
$arrayElemAt: [
"$arr",
0
]
}
}
}
])
You need to match at the first time to get the document and rest of thing arrayElementAt can manage.

Convert array of Objects into a grouped array of Objects Typescript

I'm trying to convert an array of objects like this:
[{grandParentField:'grandParent1', parentField:'parent1', childField: 'child1'},
{grandParentField:'grandParent1', parentField:'parent1', childField: 'child2'},
{grandParentField:'grandParent2', parentField:'parent1', childField: 'child3'},
{grandParentField:'grandParent2', parentField:'parent2', childField: 'child4'}]
into this form:
[
{
text: 'grandparent1',
items: [
{
text: 'parent1',
items: [{ text: 'child1' }, { text: 'child2' }]
}
]
},
{
text: 'grandparent2',
items: [
{
text: 'parent1',
items: [{ text: 'child3' }]
},
{
text: 'parent2',
items: [{ text: 'child4' }]
}
]
}
]
This Thread is similar to what I want, but not quite.
children will always be unique, but parents can have multiple grandparents.
Honestly I've tried so many things I'm not even sure which one to include as an example of what has gotten me closest.
Something like this but able to take in an array of Objects, and pump out the {text: string, items:[{text: string, items:[{text:string]]} structure:
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {3: ["one", "two"], 5: ["three"]}
Recursive approach, should work for every n-nested input that you will provide:
const input =[{grandParentField:"grandParent1",parentField:"parent1",childField:"child1"},{grandParentField:"grandParent1",parentField:"parent1",childField:"child2"},{grandParentField:"grandParent2",parentField:"parent1",childField:"child3"},{grandParentField:"grandParent2",parentField:"parent2",childField:"child4"}];
const nestedGroupBy = (nodes, order, orderIdx = 0) => {
const key = order[orderIdx]
let grouped = nodes.reduce((acc, e, i) => {
let node = acc.find(x => x.text == e[key])
if (!node) {
node = { text: e[key], items: [] }
acc.push(node)
}
node.items ? node.items.push(e) : node.items = [e]
return acc
}, [])
if (order[orderIdx + 1])
grouped = grouped.map(e => ({
text: e.text,
items: nestedGroupBy(e.items, order, orderIdx + 1)
}))
else
grouped = grouped.map(e => ({ text: e.text }) )
return grouped
}
const res = nestedGroupBy(input, Object.keys(input[0]))
console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Without getting too crazy with types, I'd say that you want your output to be of this shape:
interface Tree {
text: string,
items?: Tree[]
}
So let's make a function called group() which takes your array and a list of keys that you want to process in the order they should be processed. So for your example it would be used like this:
const data = [
{ grandParentField: 'grandParent1', parentField: 'parent1', childField: 'child1' },
{ grandParentField: 'grandParent1', parentField: 'parent1', childField: 'child2' },
{ grandParentField: 'grandParent2', parentField: 'parent1', childField: 'child3' },
{ grandParentField: 'grandParent2', parentField: 'parent2', childField: 'child4' }
];
const groupedData = group(data, "grandParentField", "parentField", "childField");
Here's the implementation of group():
function group(data: Array<Record<string, string>>, key: string, ...otherKeys: string[]): Tree[] {
const objMap: Record<string, any[]> = {}
for (const d of data) {
if (!(d[key] in objMap)) {
objMap[d[key]] = []
}
objMap[d[key]].push(d);
}
return Object.keys(objMap).map(k => otherKeys.length ?
{
text: k,
items: group(objMap[k], otherKeys[0], ...otherKeys.slice(1))
} : {
text: k
}
);
}
First we group the elements from data into a dictionary of arrays called objMap, where each element d goes into the key of objMap at d[key] (so the first element goes into the key named "grandParent1" if key is "grandParentField").
Once this grouping is done, we return a new array by walking through objMap's keys. If we have no otherKeys, we just return an array of {text: string} elements using the keys of objMap as the text field. If we do have other keys, then we need to recursively call group() on the elements stored in objMap at the proper key.
You can verify that this works for your example:
console.log(JSON.stringify(groupedData, undefined, 2));
/* [
{
"text": "grandParent1",
"items": [
{
"text": "parent1",
"items": [
{
"text": "child1"
},
{
"text": "child2"
}
]
}
]
},
{
"text": "grandParent2",
"items": [
{
"text": "parent1",
"items": [
{
"text": "child3"
}
]
},
{
"text": "parent2",
"items": [
{
"text": "child4"
}
]
}
]
}
] */
Playground link to code

how to take array values as key value pair in angular

I'm new to api. I have two arrays let it be A and B, both A and B contains json response,
Array A has the following data.
{
"servers": [
{
"links": [
{
"href": ,
"rel": "self"
},
{
"href": ",
"rel": "bookmark"
}
],
"rel": "bookmark"
}
]
},
"OS-EXte": "active",
"OS-TR:instance_name": "instance-000",
"OS-SRV-Uched_at": "20200",
"flavor": {
"id": "fe183ca7-610f-4db4-934",
"links": [
{
"href":
"rel": "bookmark"
}
]
},
and so on and array B has
{
"flavors": [
{
"name": "ti",
"links": [
{
"href": "",
"rel": "self"
},
],
"ram": 8192,
"OS-FLV-DISABLEse,
},
{
I need to take all the flavor id from array A which is matching in array B.
let servers = [{
flavor: {
id: "1",
links: [{
rel: "bookmark"
}]
}
}, {
flavor: {
id: "2",
links: [{
rel: "any"
}]
}
}]
let flavors = [{
name: "ti",
ram: 8192,
id: "1"
}, {
name: "ti",
ram: 8192,
id: "2"
}, {
name: "ti",
ram: 8192,
id: "3"
}]
let serverFlavors = servers.map(s => s.flavor.id)
let newArray = flavors.filter(f => serverFlavors.includes(f.id))
console.log(newArray)
If your data is json, you can parse the json and then do the above.
parse JSON like
JSON.parse(<strigifiedJSON>)
I think you can first map all the flavor Id from Array A to the new Array.
And then filer Array B from mapped Flavor Array .
Assuming Servers is Array A -
let serverFlavor = servers.map(row => { row.flavor.id});
let filteredRam = flavors.filter(row => serverFlavor.find((a) => a == row.id));
Then you can use reduce function on filteredRam Array .

Remove object from nested array if array is empty in Typescript

How can I remove the object if the nested array is empty. Like I have an array:
pokemonGroups = [
{
name: 'Grass',
pokemon: [
'bulbasaur-0', 'Bulbasaur', 'oddish-1','Oddish','bellsprout-2', 'Bellsprout'
]
},
{
name: 'Water',
pokemon: [
]
}]
So In this we have an empty array
{
name: 'Water',
pokemon: []
}
So I want to remove this object and my array should be like:
pokemonGroups = [
{
name: 'Grass',
pokemon: [
'bulbasaur-0', 'Bulbasaur', 'oddish-1','Oddish','bellsprout-2', 'Bellsprout'
]
}
]
You can use filter:
pokemonGroups = pokemonGroups.filter(group => group.pokemon.length != 0);
You can iterate your array and use array.splice()
var pokemonGroups = [{
name: 'Grass',
pokemon: [
'bulbasaur-0', 'Bulbasaur', 'oddish-1', 'Oddish', 'bellsprout-2', 'Bellsprout'
]
},
{
name: 'Water',
pokemon: [
]
}
]
for (var i = 0; i < pokemonGroups.length; i++) {
if (pokemonGroups[i]['pokemon'].length == 0) {
pokemonGroups.splice(i, 1);
}
}
console.log(pokemonGroups)

Resources