i am trying to check my inner array id same as dispatched id, table example
{
_id :1,
name: sagar elias jacky
Amenities :[{ id: 100, title : hi },{ id: 101, title : hallo } ]
}
checking dispatched id exit or not using map,
return { ...state,
items : {...state.items,
Amenities : { ...state.items.Amenities
.map(x=> x._id === action.dispatchedID ? {...x,deleting: true} : x ) }}}
but it will return with non array Amenities, like
Amenities:
0: { id: 100, title : hi },
1: { id: 101, title : hallo }
i want this to
Amenities:Array(2)
0: { id: 100, title : hi },
1: { id: 101, title : hallo }
When you spread an array inside {}, it creates an object with indexes of array as keys
const array = [{a:1}, {a:2}]
console.log({...array})
So, change
Amenities : { ...state.items.Amenities
.map(x=> x._id === action.dispatchedID ? {...x,deleting: true} : x ) }
to:
Amenities : [ ...state.items.Amenities
.map(x=> x._id === action.dispatchedID ? {...x,deleting: true} : x ) ]
Related
I have this kind of dictionary:
INPUT
movies = {
'big' : {
actors : ['Elizabeth Perkins', 'Robert Loggia']
},
'forrest gump' : {
actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
},
'cast away' : {
actors : ['Helen Hunt', 'Paul Sanchez']
}
};
and I want to use this dictionary to get a different one. For example, I have to make a function called "moviesWithActors" that will received two arguments: "movies" and "actor". Actor could be "Tom Hanks", so when you find that he was on the movie, you don't add to the nested array, but if wasn't, you add.
OUTPUT
movies = {
'big' : {
actors : ['Elizabeth Perkins', 'Robert Loggia', 'Tom Hanks']
},
'forrest gump' : {
actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
},
'cast away' : {
actors : ['Helen Hunt', 'Paul Sanchez', 'Tom Hanks]
}
};
I do this:
for (const value of Object.values(newMovies)){
console.log(value.actors)
for (const act of value.actors){
//console.log(act)
if (act == actor) {
console.log("Ok, not add")
}else{
console.log("Here I have to add");
}
}
}
where "newMovies" is a copy of "movies" and "actor = "Tom Hanks" but I can't add to the array in actors: [ ... ]. Any suggestion? Can I use map() ?
As per the requirement what I understood is that there is an existing array of movies object and you want to assign a hero in those movies. We have to ignore if the passed hero name is already there for that movie else add that hero under that movie. If my understanding is correct, Here you go :
const movies = {
'big' : {
actors : ['Elizabeth Perkins', 'Robert Loggia']
},
'forrest gump' : {
actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
},
'cast away' : {
actors : ['Helen Hunt', 'Paul Sanchez']
}
};
function updateMoviesList(obj, heroName) {
Object.keys(obj).forEach(key => {
if (!obj[key].actors.includes(heroName)) {
obj[key].actors.push(heroName)
}
})
return obj;
}
console.log(updateMoviesList(movies, 'Tom Hanks'));
You can use Push()
Like this from docs
let sports = ['soccer', 'baseball']
let total = sports.push('football', 'swimming')
console.log(sports) // ['soccer', 'baseball', 'football', 'swimming']
console.log(total.length) // 4
To access array inside dictionary you have first to access it
movies['big']['actors'].push('New Actor')
For not be "hard coded", if you do this?
let actor = 'Tom Hanks'
for (const value of Object.values(newMovies)){
for (const act of value.actors){
if (value.actors.includes(actor)) { //Here you check if actor contains in array
console.log("Ok, not add")
}else{
console.log("Here I have to add");
value.actors.push(actor) //if not push to array
}
}
}
I was suggested to use map instead and the class Object...
function actorInMovies(movies, actor) {
let mappedObject = { ...movies};
Object.entries(movies).map(movie => {
const movieName = movie[0];
const actors = movie[1].actors;
if (!actors.includes(actor))
actors.push(actor);
mappedObject = {
...mappedObject,
[movieName]: { actors }
};
});
return mappedObject
}
function main(){
const movies = {
'big' : {
actors : ['Elizabeth Perkins', 'Robert Loggia']
},
'forrest gump' : {
actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
},
'cast away' : {
actors : ['Helen Hunt', 'Paul Sanchez']
}
};
const actor = 'Tom Hanks';
console.log(actorInMovies(movies, actor))
}
main();
Some time ago I asked a question about how to filter array based on its key today this function but i am working a new implementation that I'm doing.
create array on basis of object's child
But I'm doing a refactoring of how I treat the field value because before I just need the first object and its value [0].value now I need to expand this logic to work with array I'll leave some examples below.
My Code I'm currently using
https://codesandbox.io/s/lodash-tester-forked-fcdmy1?file=/index.js
Original, unfiltered data from API:
[
{
"_id" : ObjectId("62548802054c225fe560f41a"),
"test" : [
"taetea",
"atty",
],
"Peso" : [
{
"_id" : "624f2ab363dd92f2101de167",
"value" : "255"
}
],
}
]
Expected result for table data:
[
{
"_id" : "62548802054c225fe560f41a",
"test1":"taetea",
"test2":"atty",
"Peso":"255"
},
{
...
},
]
Anyone who can help I'm grateful I will repay with rep+ and my eternal thanks xD
As i understand,you want to use title property from the table Columns & search it in the API data.If the title property represents an array of strings,then add all the strings otherwise add the value property.
const apiData = [
{
"_id" : "62548802054c225fe560f41a",
"test" : [
"taetea",
"atty",
],
"Peso" : [
{
"_id" : "624f2ab363dd92f2101de167",
"value" : "255"
}
],
}
];
const tableData = [
{
title: "Peso",
dataIndex: "peso",
key: "peso",
},
{
title: "test",
children: [
{
title: "ex: ${title} field ${title.length}",
dataIndex: "ex: ${title} + ${title.length}",
key: "ex: ${title} + ${title.length}",
},
{
title: "ex: ${title} field ${title.length}",
dataIndex: "ex: ${title} + ${title.length}",
key: "ex: ${title} + ${title.length}",
},
],
},
];
const tableKeys = tableData.map(t => t.title)
const output = []
apiData.forEach(obj => {
const data = []
Object.keys(obj).filter(key => tableKeys.includes(key)).forEach(key =>{
if(typeof obj[key][0]=== 'string'){
data.push(...obj[key].map((val,index) => ({[`${key}${index+1}`]:val})))
}else{
data.push({[key]: obj[key][0].value})
}
})
// Add the id of the the api data & spread the objects collected
output.push({'_id':obj._id,
...data.reduce((map,elem)=>({...map,...elem}),
{})})
})
console.log('output',output)
Hii here is my simple logical question
this is my reference array
referenceArray =[{name : "animal" , source :['duck', 'cat'], target:['water', 'ground']},
{name : "car" , source :['tata', 'kia'], target:['tiago', 'sector']},
{name : "bike" , source :['honda', 'hero'], target:['livo', 'xtream']}
]
this is i want to modify the source and target array with the above referenceArray array
originalArray =[{source : 'water' , target : 'hero'},
{source : 'tata' , target : 'ground'},
{source : 'livo' , target : 'kia'},
]
but i want the final output like this
originalArray =[{source : 'animal' , target : 'bike'},
{source : 'car' , target : 'animal'},
{source : 'bike' , target : 'car'},
]
can anyone help me out please that is soo appreciatable
You can simply build a Map of the reference array with each source and target elements keyed against the name, then map over the originalArray accessing the Map. Keep in mind this does nothing to avoid possible overlap of source and target arrays.
const referenceArray = [{ name: "animal", source: ['duck', 'cat'], target: ['water', 'ground'] }, { name: "car", source: ['tata', 'kia'], target: ['tiago', 'sector'] }, { name: "bike", source: ['honda', 'hero'], target: ['livo', 'xtream'] }];
const originalArray = [{ source: 'water', target: 'hero' }, { source: 'tata', target: 'ground' }, { source: 'livo', target: 'kia' },]
const referenceMap = new Map()
for (const { name, source, target } of referenceArray) {
for (const k of [...source, ...target]) {
referenceMap.set(k, name);
}
}
const result = originalArray.map(({ source, target }) => (
{
source: referenceMap.get(source),
target: referenceMap.get(target)
}
));
console.log(result)
I have an array in my state :
projects: [
{ title: 'todo 1', person: 'Sam', status: 'ongoing'},
{ title: 'project', person: 'Jack', status: 'complete' },
{ title: 'Design video', person: 'Tim', status: 'complete' },
{ title: 'Create a forum', person: 'Jade', status: 'overdue' },
{ title: 'application', person: 'Jade', status: 'ongoing'},],
From this array (projects), I would like to generate a new array with Javascript and to get this result :
totalByPersonAndStatus : [
{person : 'Sam', complete: 0, ongoing: 1, overdue: 0 },
{person : 'Jack', complete: 1, ongoing: 0, overdue: 0 },
{person : 'Tim', complete: 1, ongoing: 0, overdue: 0 },
{person : 'Jade', complete: 0, ongoing: 1, overdue: 1 },]
I tried it
totalProjectsByPersonAndStatus: state => {
state.projects.forEach(name => {
state. totalByPersonAndStatus["name"] = name.person;
});
return state. totalByPersonAndStatus;
The problem, if a make a console.log(this.totalByPersonAndStatus) I have an object with only the data of projects.name [name: "Jade", __ob__: Observer]
Can you help me ?
Thank you
You can use reduce
let projects =[{title:'todo1',person:'Sam',status:'ongoing'},{title:'project',person:'Jack',status:'complete'},{title:'Designvideo',person:'Tim',status:'complete'},{title:'Createaforum',person:'Jade',status:'overdue'},{title:'application',person:'Jade',status:'ongoing'},]
let desired = projects.reduce((output,{person,status}) => {
if( output[person] ){
output[person][status]++
} else {
output[person] = {
person,
complete: Number(status==='complete'),
ongoing: Number(status==='ongoing'),
overdue: Number(status==='overdue')
}
}
return output;
},{})
console.log(Object.values(desired))
Create a new Set for people and statuses by iterating through the projects, a set has only unique values so sets are a convenience, iterate through your people set creating a new object with all the statuses initialized to 0, then iterate over the projects to increment the various statuses that apply. This method allows any number of new statuses to be added without changing the code - dynamic.
var people = new Set();
var status = new Set();
projects.forEach((p)=>{
people.add(p.person);
status.add(p.status);
});
var totalByPersonAndStatus = [];
people.forEach((person)=>{
let peeps = { "person": person };
status.forEach((stat)=>{
peeps[stat] = 0;
});
projects.forEach((project)=>{
if (project.person === person) { peeps[project.status]++; }
});
totalByPersonAndStatus.push(peeps);
});
You could use reduce and destructuring like this:
const projects=[{title:'todo 1',person:'Sam',status:'ongoing'},{title:'project',person:'Jack',status:'complete'},{title:'Design video',person:'Tim',status:'complete'},{title:'Create a forum',person:'Jade',status:'overdue'},{title:'application',person:'Jade',status:'ongoing'}]
const merged = projects.reduce((acc,{person,status})=>{
acc[person] = acc[person] || { person, ongoing:0, complete:0, overdue:0}
acc[person][status]++;
return acc;
},{})
console.log(Object.values(merged))
The goal is create an object merged with each person as key and then increment based on the statuses:
{
"Sam": {
"person": "Sam",
"ongoing": 1,
"complete": 0,
"overdue": 0
},
"Jack": {
}
...
}
Then use Object.values, to get the final array.
You could make it a one-liner:
const projects=[{title:'todo 1',person:'Sam',status:'ongoing'},{title:'project',person:'Jack',status:'complete'},{title:'Design video',person:'Tim',status:'complete'},{title:'Create a forum',person:'Jade',status:'overdue'},{title:'application',person:'Jade',status:'ongoing'}],
output = Object.values(projects.reduce((a,{person,status})=>
((a[person] = a[person] || {person,ongoing:0,complete:0,overdue:0})[status]++,a),{}))
console.log(output)
Doc:
{
_id: 5150a1199fac0e6910000002,
name: 'some name',
items: [{
id: 23,
name: 'item name 23'
},{
id: 24,
name: 'item name 24'
}]
}
Is there a way to pull a specific object from an array? I.E. how do I pull the entire item object with id 23 from the items array.
I have tried:
db.mycollection.update({'_id': ObjectId("5150a1199fac0e6910000002")}, {$pull: {id: 23}});
However I am pretty sure that I am not using 'pull' correctly. From what I understand pull will pull a field from an array but not an object.
Any ideas how to pull the entire object out of the array.
As a bonus I am trying to do this in mongoose/nodejs, as well not sure if this type of thing is in the mongoose API but I could not find it.
try..
db.mycollection.update(
{ '_id': ObjectId("5150a1199fac0e6910000002") },
{ $pull: { items: { id: 23 } } },
false, // Upsert
true, // Multi
);
I have a document like
I have to delete address from address array
After searching lots on internet I found the solution
Customer.findOneAndUpdate(query, { $pull: {address: addressId} }, (err, data) => {
if (err) {
return res.status(500).json({ error: 'error in deleting address' });
}
res.json(data);
});
my database:
{
"_id" : ObjectId("5806056dce046557874d3ab18"),
"data" : [
{ "id" : 1 },
{ "id" : 2 },
{ "id" : 3 }
]
}
my query:
db.getCollection('play_table').update({},{$pull:{"data":{"id":3}}},{multi:true}
output:
{
"_id" : ObjectId("5806056dce046557874d3ab18"),
"data" : [
{ "id" : 1 },
{ "id" : 2 }
]
}
You can try it also:
db.getCollection('docs').update({ },{'$pull':{ 'items':{'id': 3 }}},{multi:true})
For a single record in array:
db.getCollection('documents').update(
{ },
{'$pull':{ 'items':{'mobile': 1234567890 }}},
{new:true}
);
For a multiple records with same mobile number in array:
db.getCollection('documents').update(
{ },
{
$pull: {
items: { mobile: 1234567890 }
}
},
{ new:true, multi:true }
)
Use $pull to remove the data
return this.mobiledashboardModel
.update({"_id": args.dashboardId}, { $pull: {"viewData": { "_id": widgetId}}})
.exec()
.then(dashboardDoc => {
return {
result: dashboardDoc
}
});
Kishore Diyyana:
If you want to remove all elements including the key of the element attributes list.
Here is the example of mongoDB unset operator:
db.UM_PREAUTH_CASE.update(
{ 'Id' : 123}, { $unset: { dataElements: ""} } )
JSON Look like this:
{ "Id":123,"dataElements" : [ { "createdBy" : "Kishore Babu Diyyana", "createdByUserId" : 2020 }, { "createdBy" : "Diyyana Kishore", "createdByUserId" : 2021 } ] }