How to turn array of objects in unique array? - javascript

This is my initial data:
const data = [
{
"user":{
"amount":"1",
"date":"2020-07-31T18:34:48.635Z",
"shiftSelected":"10:00"
}
},
{
"user":{
"name":"Name",
"surname":"aaa",
"obs":"eee"
}
}
]
I'm trying to turn an array of objects in unique array. This is my output:
const newData = {
amount: "1",
date: "2020-07-31T18:34:48.635Z",
shiftSelected: "10:00",
name: "Name",
surname:"aaa",
obs:"eee"
}
I can iterate over the array with a map call: let b = data.map(item => item.user), but I need to write more code to join then. I know that it's possible to do it with one unique logic. I tried but without successful.

You can use reduce with Object.assign to merge the properties of the objects. Note that with this method, later properties will overwrite previous ones.
const data = [
{
"user":{
"amount":"1",
"date":"2020-07-31T18:34:48.635Z",
"shiftSelected":"10:00"
}
},
{
"user":{
"name":"Name",
"surname":"aaa",
"obs":"eee"
}
}
];
const result = data.reduce((acc,{user})=>Object.assign(acc,user), {});
console.log(result);
Object spread syntax will also work.
const data = [
{
"user":{
"amount":"1",
"date":"2020-07-31T18:34:48.635Z",
"shiftSelected":"10:00"
}
},
{
"user":{
"name":"Name",
"surname":"aaa",
"obs":"eee"
}
}
];
const result = data.reduce((acc,{user})=>({...acc, ...user}), {});
console.log(result);

const data = [
{
"user":{
"amount":"1",
"date":"2020-07-31T18:34:48.635Z",
"shiftSelected":"10:00"
}
},
{
"user":{
"name":"Name",
"surname":"aaa",
"obs":"eee"
}
}
]
let b = data.reduce((acc, rec) => {
const { user } = rec
return { ...acc, ...user}
}, {} )
console.log(b)

use this after map over datas this is not a logic but.....
const x = data.map(obj => obj.user);
function flatObj(arr) {
const res = {};
arr.forEach(y => {
for(const key in y) {
res[key] = y[key];
}
})
return res;
}
const resault = flatObj(x);

Related

Javascript combine object

I'm trying to transform the object received from the to a format used in backend.
I receive this object
{
'User.permissions.user.view.dashboard': true,
'Admin.permissions.user.view.dashboard': true,
'Admin.permissions.admin.view.dashboard': true,
}
The first part of the key (User, Admin) is the role name, the rest is the role. I need to combine this object into an object that has role names as keys for arrays containing the permission strings. The final result should look like this
{
'User': [
'permissions.user.view.dashboard'
],
'Admin': [
'permissions.user.view.dashboard',
'permissions.user.admin.dashboard;
]
}
So far I managed to get this result, but I'm not sure how to combine the results
const data = JSON.parse(req.body)
const permissions = Object.keys(data).map((key) => {
const permParts = key.split('.')
return {[permParts[0]]: permParts.slice(1).join('.')}
})
console.log(permissions);
[
{ User: 'permissions.user.view.dashboard' },
{ Admin: 'permissions.admin.view.dashboard' },
{ Admin: 'permissions.user.view.dashboard' }
]
const roleData = {
'User.permissions.user.view.dashboard': true,
'Admin.permissions.user.view.dashboard': true,
'Admin.permissions.admin.view.dashboard': true,
};
const mappedData = Object.keys(roleData).reduce((acc, entry) => {
const dotIndex = entry.indexOf('.');
const parts = [entry.slice(0,dotIndex), entry.slice(dotIndex+1)];
acc[parts[0]] ??= [];
acc[parts[0]].push(parts[1]);
return acc;
}, {});
console.log(mappedData);
You can use reduce function:
const result = permissions.reduce((acc, cur) => {
const key = Object.keys(cur)[0]
if (acc[key]) {
acc[key] = [...acc[key], cur[key]]
} else {
acc[key] = [cur[key]]
}
return acc
}, {})

How to update an array inside an array of objects with useState function component

How to update array inside array use state function component
the array is inside the setTask() and how to use setTask() and add new_photo in photos
const new_photo = "testing2.png"; <------------ insert this value in photos
const [task, setTask] = useState([
{
task_id: 123,
title: "sample",
photos: ["testing1.png"] <------------ here
}
])
Result should be like this:
[
{
task_id: 123,
title: "sample",
photos: ["testing1.png","testing2.png"]
}
]
setTask((oldTasks) => {
const myTask = oldTasks.find(t => t.task_id === 123)
return [
...oldTasks.filter(ot => ot.task_id != 123),
{
...myTask,
photos: [...myTask.photos, new_photo],
}
]
})
Ref: spread operator and asynchronous state update
const new_photo = "testing2.png"; // <------------ insert this value in photos
const [task, setTask] = useState([
{
task_id: 123,
title: "sample",
photos: ["testing1.png"] // <------------ here
}
])
const arrayPush = (ID) => {
setTask((element) => {
element.forEach((e) => {
if (e.task_id === ID) {
e.photos.push(new_photo);
}
});
});
console.log(task);
}
const arrayPush2 = (ID) => {
let taskCopy = Array.from(task)
taskCopy.forEach((element) => {
if (element.task_id === ID) {
element.photos.push(new_photo);
}
});
setTask(taskCopy)
};
arrayPush(123)
arrayPush2(123)

how to push the object keys and values to array

I need to push the key value pair to new array and should build the mongodb $match query.
const queryFormat = (payload) => {
delete payload.userEventId
var query = {}
var res = []
for(key in payload) {
if(typeof(payload[key])) {
res.push({ [key]: payload[key] })
}
else {
res.push({"$in" :{ [key]: payload[key] }})
}
}
console.log(res[3])
query['$match'] = {"$and" :res}
console.log(query)
}
const payload = {
id :1,
name : 'Alfred',
location : 'moon',
values : [{name: 'u',age:9}]
}
queryFormat(payload)
expected output
{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u"},{age: 9}]} }]}}
output I got
{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u",age: 9}]} }]}}
How to deal with it
Thanks!!
Currently you are specifying the key as "key"
Use [] to specify that you need the value of key as the key
const queryFormat = (payload) => {
delete payload.userEventId
var query = {}
var res = []
for(key in payload) {
res.push({ [key]: payload[key] })
}
query['$match'] = {"$and" :res}
console.log(query)
}
const payload = {
id :1,
name : 'Alfred',
location : 'moon'
}
queryFormat(payload)

How to map Array of Objects and return the length of each Object's value?

I want to check the value of every key in each object and write its length.
I tried doing this:
const a = [
{
name:"Bill",
age:'',
old:''
}
]
const myF = (arr) => {
return arr.map((i,k) => {
console.log(Object.keys(i))
return{ [Object.keys(i)]: ''}
})
}
console.log(myF(a))
I expect to get:
{
name:4,
age:0,
old:0
}
You can map it by taking entries. Let me know if this is what something you need:
var a = [ { name:"Bill", age:'', old:''}];
var result = a.map(obj=>Object.fromEntries(Object.entries(obj).map(([k,v])=>[k, v ? v : v.length])));
var result2 = a.map(obj=>Object.fromEntries(Object.entries(obj).map(([k,v])=>[k, v.length])));
console.log(result);
console.log(result2)
const a = [
{
name:"Bill",
age:'',
old:''
}
]
var b = a.map((x) =>{
if(x.age == '') {
x.age = 0;
}
if(x.old == '') {
x.old = 0;
}
return x;
})
console.log(b)

Check if every id has an existing object in array

I would like to check if there is an existing object for every id of an array.
const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ]
const target = [
{ _id: 'xxnQt5X8pfbcJMn6i' },
{ _id: 'Qt5X8pfbcJMn6ixxn' },
]
In this example I would like to get false, as the second ID (fbcJMn6ixxnQt5X8p) is not existing.
This should return true:
const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ]
const target = [
{ _id: 'xxnQt5X8pfbcJMn6i' },
{ _id: 'Qt5X8pfbcJMn6ixxn' },
{ _id: 'fbcJMn6ixxnQt5X8p' },
]
This is what I've tried:
ids.every(id => target.find(element => element._id === id))
You're pretty close, you need to pass a function instead of an object to find though - and I'd recommend to use some() instead of find if you only want to know about if it exists, rather than you need the object in return.
const ids = [ 'xxnQt5X8pfbcJMn6i', 'fbcJMn6ixxnQt5X8p' ]
const target = [
{ _id: 'xxnQt5X8pfbcJMn6i' },
{ _id: 'Qt5X8pfbcJMn6ixxn' },
{ _id: 'fbcJMn6ixxnQt5X8p' },
]
const allIn = ids.every(id => target.some(({_id}) => id === _id));
console.log(allIn);
With a lot of entries, it might be faster to use a Set (so we get O(n + m) instead of O(n * m)) :
const idSet = new Set(target.map(el => el._id));
const result = ids.every(id => idSet.has(id));
Since every is itself a checker method it's return true or false through the provided function. So you can simply return false:
const res = const res = ids.every(id => target._id === id);
console.log(res);
or true:
const res = ids.every(id => target._id !== id);
console.log(res);

Categories

Resources