how to push the object keys and values to array - javascript

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)

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
}, {})

React - How to convert a nested object into a array

I have the following object that I would like to convert it into an array of object and each object from the array to have the key: value[0].
object:
const obj = {
comedy: ['book1', 'book2'],
action: ['book3', 'book4'],
drama: ['book5'],
}
output
const arr = [
{comedy: 'book1'},
{comedy: 'book2'},
{action: 'book3'},
{action: 'book4'},
{drama: 'book5'},
]
So far I have tried solving this with loops and using Object.entries. But I do not get the output I need.
let result = [];
for(const [key1, value1] of Object.entries(arr)) {
for (const [key2, value2] of Object.entries(value1)) {
if(result[key2]) {
result[key2] [key1] = value2
} else {
result[key2] = {[key1]: value2}
}
}
}
console.log(result)
I have also tried to loop recalling the function inside itself. (I have found this search for the answer). But it will get stucked in a infinite loop.
const result = [];
const getArray = (obj) => {
if (!obj) return;
const {keys, ...rest} = obj;
result.push({...rest});
getArray(keys);
}
console.log('here', getArray(arr));
You could use a reduce over the entries of obj, adding objects to the accumulator for each entry in the array value:
const obj = {
comedy: ['book1', 'book2'],
action: ['book3', 'book4'],
drama: ['book5'],
}
const arr = Object.entries(obj)
.reduce((acc, [k, v]) => acc.concat(v.map(b => ({ [k] : b }))),
[]
)
console.log(arr)
Try this
function nestedObjectIntoArray(obj) {
const arr = [];
for (const key in obj) {
for (const value of obj[key]) {
const obj = {};
obj[key] = value;
arr.push(obj);
}
}
return arr;
}
const obj = {
comedy: ["book1", "book2"],
action: ["book3", "book4"],
drama: ["book5"],
};
console.log(nestedObjectIntoArray(obj));
const obj = {
comedy: ['book1', 'book2'],
action: ['book3', 'book4'],
drama: ['book5'],
}
const result = Object
.keys(obj)
.reduce((acc, key) =>
[...acc, ...obj[key]
.map((value) => ({[key]: value}))],
[]
)
console.log(result)
We can also achieve this by just using Array.forEach() method.
Live Demo :
// Input object
const obj = {
comedy: ['book1', 'book2'],
action: ['book3', 'book4'],
drama: ['book5'],
};
// Declare a variable to store the final result.
const arr = [];
// Iterate the input object based on the keys and build the final object.
Object.keys(obj).forEach(key => {
obj[key].forEach(item => {
arr.push({ [key]: item })
})
});
// Result
console.log(arr);
we can achieve this way too
const obj = {
comedy: ['book1', 'book2'],
action: ['book3', 'book4'],
drama: ['book5'],
}
const fun = (ar, temp)=>{
for(x in ar){
ar[x].map((e, i)=> {
var data = {[x] : e}
temp.push(data)
})}
return temp
}
console.log(fun(obj , []))

How to turn array of objects in unique array?

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);

How to get the object key it has the value

I have a filter component which user can choose any data to filter so I store this data in state.when I want to create a params for query some of the field not choosen by user I only wanna get the one which has value here is the code ;
function createParams(params = {}) {
let result = "?";
for (let key in params) {
result += `${key}=${params[key]}&`;
}
return result;
}
export async function callApi(params) {
const parameters = createParams(params);
try {
const response = await fetch(URL+ parameters);
const res = await response.json();
return res;
} catch (error) {
console.error(error)
throw error;
}
}
export const requestProperties = (params) => callApi(params);
const requestedParams = {type:"Fiat", model:"500", color:""};
I only want to get the type and model because it has been choosen by user to filter. I dont wanna include the colour
Thank you..:)
You can take entries and then filter out the records.
var requestedParams = {type:"Fiat", model:"500", color:""};
var result = Object.fromEntries(Object.entries(requestedParams).filter(([k,v])=>v));
console.log(result);
You can destructure the object if you only want to exclude one key-value pair
const requestedParams = {type:"Fiat", model:"500", color:""};
const exclude = 'color';
const {[exclude]: remove, ...rest} = requestedParams;
console.log(rest);
If you have multiple key-value pairs that you want to exclude, you can use reduce function
const requestedParams = { type: "Fiat", model: "500", color: "" };
const res = Object.entries(requestedParams).reduce((acc, curr) => {
return curr[1] ? (acc[curr[0]] = curr[1], acc) : acc;
}, {});
console.log(res);

Modifying an array of objects with uuid keys

I've got add
I've got delete
now I need modify
add just adds to the pile haphazardly
delete is able to do it's work with surgical precision because it uses key to find it's culprit :
addInput = (name) => {
const newInputs = this.props.parameters;
newInputs.push({
name,
key: uuid(),
value: { input: '' },
icon: { inputIcon: 0 },
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
removeInput = (key) => {
const newInputs = this.props.parameters.filter(x => x.key !== key);
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
how do I modify (for example set the value back to '' without deleting and recreating the item) ?
modifyInput = (key) => {
?????
};
You can use Array.prototype.find()
modifyInput = (key) => {
const match = this.props.parameters.find(x => x.key === key);
// do stuff with matched object
};
You can map through the parameters and then modify when you find a match:
modifyInput = (key) => {
const newInputs = this.props.parameters.map(x => {
if (x.key === key) {
x.modification = true;
}
return x;
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
var empMap= {};
//initialize empMap with key as Employee ID and value as Employee attributes:
//Now when salary updated on UI from 100 - 300 you can update other fields
var e=empMap[id];
if(e){
e.Salary=newSalary;
e.YearlySalary = newSalary*12;
e.Deductions = e.YearlySalary*0.2;
empMap[id]=e;
}

Categories

Resources