I have got array of nested array of objects .
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
I want to convert array to this format of objects and I want to get this output
let permission ={
group:["1"],
topGroup:["2"]
}
How can I do this ?
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
const converted = data.reduce((a,b) => {
const onlyKey = Object.keys(b)[0];
a[onlyKey] = b[onlyKey].map(i => i.label);
return a;
}, {})
console.log(converted)
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
let permission = {};
data.forEach(val =>{
for(prop in val){
permission[prop] = [val[prop][0]["label"]]
}
})
console.log(permission)
Give this a upvote if this is what you want.
Assuming the data is going to have labels as in that format forever, you could use something like that
const data = [{"group":[{"label":"1"}]},{"topGroup":[{"label":"12"}]}];
// The dict variable under here is the second parameter of reduce that I passed it `{}`.
// The ind variable is the data at the index of the array.
var newData = data.reduce(function(dict, ind){
// You basically get the keys and the values and put them in place
// and return the last state to the reduce function.
dict[Object.keys(ind)] = Object.values(ind)[0][0]["label"];
return dict;
}, {})
console.log(newData)
Use destructuring and Object.fromEntries.
const data = [{ group: [{ label: "1" }] }, { topGroup: [{ label: "2" }] }];
const permission = Object.fromEntries(
data.map(item => {
const [[key, [obj]]] = Object.entries(item);
return [key, Object.values(obj)];
})
);
console.log(permission);
Related
I have a problem to filters data inside the array of objects by an array of objects. I already try using filters combine with the includes method but returning an empty array.
let's say I have array an array called listOfPermissions.
listOfPermissions = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
{name:'C',IsChecked:true}
]
Than i want to filter the list with permissionOnRole array
permissionOnRole = [
{name:'C',IsChecked: true}
]
The goals i want to achieve
result = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
]
this is my code
const setUncheckPermissions = () => {
const permissionsOnRole = role.permissions.map(it => ({name: it, isChecked: true}))
const listOfAllPermissions = props.permissions.map((permission) => {return {name: permission['name'], isChecked: true}});
let result = listOfAllPermissions.filter(item => permissionsOnRole.includes(item));
console.log(listOfAllPermissions)
}
please help me to solve this problems
Thank you in advance
Just use filter
const listOfPermissions = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
{name:'C',IsChecked:true}
]
const permissionOnRole = [
{name:'C',IsChecked: true}
]
const result = listOfPermissions.filter(item => !!permissionOnRole.find(i => i.name !== item.name))
console.log(result)
Hello I'm trying to create an object that includes under the same property name a bunch of array values,
This what I'm trying
const quiz = [
{question: 'Who is the main character of DBZ',
options: ['Vegetta','Gohan','Goku']}
]
const newObj = {
options: []
}
quiz.forEach((item)=>{
item.options.forEach((item, index)=>{
newObj.options[`name${index}`] = item
})
})
expected value =
newObj = {
options: [{name: 'Vegetta'},{name:'Gohan'},{name:'Goku'}]
}
actual value received =
newObj = {
{ options: [ name0: 'Vegetta', name1: 'Gohan', name2: 'Goku' ] }}
Thanks in advance!
As you've noticed, newObj.options[`name${index}`] = item creates a new key on your options array, and sets that to item. You instead want to push an object of the form {name: item} into your array. There are a few ways you could go about this, one way is to use .push() like so:
quiz.forEach((item)=>{
item.options.forEach((item)=>{
newObj.options.push({name: item});
})
});
while not as common, you can also use set the current index of options, which is slightly different to the above example, as it will maintain the same index, which can be important if quiz is a sparse array that you want to keep the same indexing of on options:
quiz.forEach((item)=>{
item.options.forEach((item, index)=>{
newObj.options[index] = {name: item};
})
});
Example of the difference:
const arr = [1, 2,,,5]; // sparse array
const pushRes = [];
const indxRes = [];
arr.forEach(n => pushRes.push(n));
arr.forEach((n, i) => indxRes[i] = n);
console.log("Push result", pushRes);
console.log("Index result", indxRes);
For a different approach, you also have the option of using something like .flatMap() and .map() to create your options array, which you can use to create newObj:
const quiz = [
{question: 'Who is the main character of DBZ',
options: ['Vegetta','Gohan','Goku']}
];
const options = quiz.flatMap(({options}) => options.map(name => ({name})));
const newObj = {options};
console.log(newObj);
i'm new here, i have problem that i can not solve.
I have 2 different arrays:
The first array - contains ratings of users with their ID name
[
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
]
The second set - contains the ratings, which I want to return to each user.
If there is a rating that is not in the second set, I will not return it
In the second set, values do not matter, only keys
[
"_assembler",
"_css",
"_python",
"_php"
]
I want to return to the first set, the handle, and all the rankings that exist in the second set.
[
{"handle":"frontend1", "_python":"3" },
{"handle":"frontend3", "_php":"4", "_python":"5" },
{"handle":"frontend4"}
]
this is what i try to do.
keys = [
"_assembler",
"_css",
"_python",
"_php"
]
source = [
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
];
result = [];
tmp = {};
source.forEach((item) => {
Object.keys(item).map(({key,value}) =>
{
if(key == "handle")
{
tmp[key]=value;
}
if(keys.includes(key))
{
tmp[key]=value;
}
})
result.push(...tmp);
tmp = {};
});
You can do this with a map utilizing a couple of other array methods such as filter, and Object methods.
const keys = [
"_assembler",
"_css",
"_python",
"_php"
]
const source = [
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
];
const result = source.map( s => ({
handle: s.handle,
...Object.fromEntries(Object.entries(s).filter(x => x[0] != "handle" && keys.includes(x[0])))
}));
console.log(result);
I tried to contrcut the object based on response coming from API.
my key is assigned this.RootKeyValue and my response is assigned to this.keyResponse
this.RootKeyValue is the key of parent of first object .
In second object based on the DynamicKey value need to create the key and values .
this.RootKeyValue = "AccountDetails";
this.keyResponse =
[
{ICICI: 2,DynamicKey: "ICICI"},
{SBI: 1.25,DynamicKey: "SBI"}
{HDFC: 1.75,DynamicKey: "HDFC"}
]
how to construct the object like below using above key and response.
Expected result :
{
AccountDetails :
{ ICICI :2 , SBI: 1.25,HDFC: 1.75 }
}
I am new to react please suggest how to construct object using the dynamic key values
You build a dynamic object using square bracket notation
const obj = { ["SomeDynamicKey"]: someValue }
So in your case you can use reduce to build the object from your array:
this.RootKeyValue = "AccountDetails";
this.keyResponse =
[
{ICICI: 2,DynamicKey: "ICICI"},
{SBI: 1.25,DynamicKey: "SBI"},
{HDFC: 1.75,DynamicKey: "HDFC"}
]
const result = {
[this.RootKeyValue] : this.keyResponse.reduce( (acc,item) => ({
...acc,
[item.DynamicKey]: item[item.DynamicKey]})
,{})
}
console.log(result)
As the give array already has the dynamic keys and associate value in same object , you can create your desired object very easily like this.
let given = [
{ICICI: 2,DynamicKey: "ICICI"},
{SBI: 1.25,DynamicKey: "SBI"},
{HDFC: 1.75,DynamicKey: "HDFC"}
] , AccountDetails = {};
given.forEach(item => {
AccountDetails[item.DynamicKey] = item[item.DynamicKey] ? item[item.DynamicKey] : '';
})
console.log(AccountDetails);
You can use square brackets to handle this very easily, e.g.
const key = 'DYNAMIC_KEY';
const obj = { [key]: 'value' };
const RootKeyValue = "AccountDetails";
const keyResponse = [
{ ICICI: 2,DynamicKey: "ICICI" },
{ SBI: 1.25,DynamicKey: "SBI" },
{ HDFC: 1.75,DynamicKey: "HDFC" }
];
const newData = { [RootKeyValue]: {} };
keyResponse.forEach(item => {
newData[RootKeyValue][item.DynamicKey] = item[item.DynamicKey];
})
console.log(newData)
I have an URL with query params like this:
myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww
after JSON parsing it convert into next structure
{
attributes[0][name]: "customer_property_number"
attributes[0][op]: "equal"
attributes[0][value]: "12"
attributes[1][name]: "feedback_tags"
attributes[1][op]: "in"
attributes[1][value]: "test 1,www"
}
In the end, I need an array that look like this:
attributes = [
{
name: 'customer_property_number',
op: 'equal',
value: '12',
},
{
name: 'feedback_tags',
op: 'in',
value: 'test 1, www',
},
]
Now does anyone know how I can then put these items into attributes array?
Thanks!
Here is the approach using URLSearchParams and going over each search param, parse and push to array of objects.
var sp = new URLSearchParams(
"myLocalSite/?attributes%5B0%5D%5Bname%5D=customer_property_number&attributes%5B0%5D%5Bop%5D=equal&attributes%5B0%5D%5Bvalue%5D=12&attributes%5B1%5D%5Bname%5D=feedback_tags&attributes%5B1%5D%5Bop%5D=in&attributes%5B1%5D%5Bvalue%5D=test+1%2Cwww"
);
var attributes = [];
for (entry of sp) {
const [attr, value] = entry;
const [index, key] = attr
.split("[")
.filter(x => x.includes("]"))
.map(x => x.slice(0, -1));
if (!attributes[Number(index)]) {
attributes[Number(index)] = {};
}
attributes[Number(index)][key] = value;
}
console.log(attributes);