Constructing object array using dynamic keys in react/Javscript - javascript

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)

Related

Can destructuring an array be used to map properties of each elements?

Suppose there is an array like this:
const a = [ {p:1}, {p:2}, {p:3} ];
Is it possible to destructure this array in order to obtain p = [1, 2, 3] ?
Because this does not work :
const [ ...{ p } ] = a; // no error, same as const p = a.p;
// p = undefined;
Edit
In response to all the answers saying that I need to use Array.prototype.map, I am aware of this. I was simply wondering if there was a way to map during the destructuring process, and the answer is : no, I need to destructure the array itself, then use map as a separate step.
For example:
const data = {
id: 123,
name: 'John',
attributes: [{ id:300, label:'attrA' }, { id:301, label:'attrB' }]
};
function format(data) {
const { id, name, attributes } = data;
const attr = attributes.map(({ label }) => label);
return { id, name, attr };
}
console.log( format(data) };
// { id:123, name:'John', attr:['attrA', 'attrB'] }
I was simply wondering if there was a way, directly during destructuring, without using map (and, respectfully, without the bloated lodash library), to retrive all label properties into an array of strings.
Honestly I think that what you are looking for doesn't exist, normally you would map the array to create a new array using values from properties. In this specific case it would be like this
const p = a.map(element => element.p)
Of course, there are some packages that have many utilities to help, like Lodash's map function with the 'property' iteratee
you can destructure the first item like this :
const [{ p }] = a;
but for getting all values you need to use .map
and the simplest way might be this :
const val = a.map(({p}) => p)
Here's a generalized solution that groups all properties into arrays, letting you destructure any property:
const group = (array) => array.reduce((acc,obj) => {
for(let [key,val] of Object.entries(obj)){
acc[key] ||= [];
acc[key].push(val)
}
return acc
}, {})
const ar = [ {p:1}, {p:2}, {p:3} ];
const {p} = group(ar)
console.log(p)
const ar2 = [{a:2,b:1},{a:5,b:4}, {c:1}]
const {a,b,c} = group(ar2)
console.log(a,b,c)

Filter an array of objects, by keys in filter object

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

JS get value of nested key with changing parent name

I need to get the value of roles in the following example.
const obj ={
id: 1,
"website.com": {
roles: ["SuperUser"]
}
}
const r = obj.hasOwnProperty("roles")
console.log(r)
Its parent objects name ("website.com") can change everytime as Im requesting it from the db. What is the best way to get this variable?
The obj would also be relatively large I just didnt include it in the example.
You could iterate over the object and exclude id. Example:
for (var x in obj) {
if (x !== 'id') {
console.log(obj[x].roles)
}
}
EDIT (to address your question edit):
If the root object has many keys, it would probably make sense to instead either move the domain from a key to a value (for example, domain: 'website.com' and move the roles up (flattening the object); or you could check for a key that looks like a domain using a regex. Example: if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/.test(x) rather than if (x !== 'id'). The regex way would probably be brittle.
EDIT 2:
You could use the hasOwnProperty check like this:
let roles
for (let x in obj) {
if (obj[x].hasOwnProperty(roles)) {
roles = obj[x])
}
}
You can get the roles by destructuring the roles property from the value of obj['website.com'].
If you want to do this dynamically, you will need to figure out key has a corresponding object with the property roles. Once you find all valid candidates, you can access the first (or whichever one you want) and then grab its value.
const hasRoles = obj => Object.entries(obj)
.filter(([key, value]) =>
value.hasOwnProperty('roles'));
const obj = {
id: 1,
"website.com": {
roles: ["SuperUser"]
}
}
const [ first ] = hasRoles(obj);
const [ website, { roles } ] = first;
console.log(`website = ${website} | roles = ${roles}`);
Alternatively, for a greedy match:
const hasRolesGreedy = obj => Object.entries(obj)
.find(([key, value]) =>
value.hasOwnProperty('roles'));
const obj = {
id: 1,
"website.com": {
roles: ["SuperUser"]
}
}
const found = hasRolesGreedy(obj);
const [ website, { roles } ] = found;
console.log(`website = ${website} | roles = ${roles}`);
only access to the nested key like this:
let roles = obj["website.com"].roles;
console.log(roles);
That way, you will get an array, then you can iterate or get a value by the index.
Since you don't know what the name is, you need to iterate over all properties and find the first with the roles property:
const testObj ={
id: 1,
"website.com": {
roles: ["SuperUser"]
}
}
const testObj2 = {
id: 2,
"anotherwebsite.com":{
roles: ["AnotherSuperUser"]
}
}
function getRoles(obj){
for(let x in obj){
if(Object.prototype.hasOwnProperty.call(obj, x))
{
if(obj[x].roles){
return obj[x].roles;
}
}
}
return undefined;
}
console.log(getRoles(testObj));
console.log(getRoles(testObj2));

how to convert nested array of objects to object of array

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

How can you destructure an array of objects in Javascript into two predefined variables in ES6?

I have an array containing one object of this form :
Array = [ { type: type, message: message } ]
I keep getting ESLint errors asking me to use object destructuring and array destructuring.
Currently my code looks like this :
let type=null;
let message=null;
if (data.length > 0) {
({ type, message } = data[0]);
}
So far this works and my variables are assigned correctly, however I am still getting the "Use array destructuring" message from ESLint.
Any help with this would be appreciated. Thank you
You can destructure the array:
let type=null;
let message=null;
if (data.length > 0) {
[{ type, message }] = data;
}
The code above is a shorter version of:
[ firstElement ] = data; // array destructruring
({ type, message } = firstElement); // object destructuring
Faly's way is good. You can also use default values when destructuring:
function test(label, data) {
// 1 -----------------------------vvvvv
let [{type = null, message = null} = {}] = data;
// 2 -----^^^^^^^---------^^^^^^^
console.log(label, type, message);
}
test("test1: ", []);
test("test2: ", [{type: "t"}]);
test("test3: ", [{type: "t", message: "m"}]);
That works because if data.length is 0, data[0] is undefined, and so triggers use of the default value {} (1) for the array part of that; within the object part of that, we use null (2) to handle any missing values on the object as well.
EsLint wants you to write
let type = null;
let message = null;
if (data.length > 0) {
[{ type, message }] = data;
}
which destructures the first item of an iterable data into the {type, message} target. (More items are ignored).
I would however recommend to use default values for the empty case:
const [{type, message} = {type:null, message:null}] = data;
or also
const [{type = null, message = null} = {}] = data;

Categories