How to group by using reduce in Javascript [duplicate] - javascript

I have an object called this.props which contains
{
actions: Object,
dirty: false,
form: "Statement",
autofill: function(),
**statement: Object**
}
statement contains
{
firstName: "John"
lastName: "Peter"
isConfirmed: true
}
I would like to extract statement object and the isConfirmed property in the same line using es6 destructuring
I've tried
const { statement: isConfirmed, isAdmin } = this.props
which I get an error when I do let a = isConfirmed, b = statement

I would like to extract statement object and the isConfirmed property in the same line
const { statement: { isConfirmed }, statement } = this.props;
That way you get both isConfirmed and the whole statement object.
References:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring

Related

How to dynamically test for typeof array within object?

I have an user object - I want to generate test for each user property and check if it's the right type. However as typeof array is an object assertion fails on array properties with "AssertionError: expected [ 1 ] to be an object".
I have therefore checked if the property is an array and then generate special test for it. I'm wondering if this is the right approach? I have a feeling I'm misssing something obvious.
Object.keys(pureUser).forEach(property =>{
// since typeof array is an object we need to check this case separately or test will fail with expecting array to be an object
if (Array.isArray(pureUser[property])) {
it(`should have property ${property}, type: array`, function () {
user.should.have.property(property);
});
} else {
it(`should have property ${property}, type: ${(typeof pureUser[property])}`, function () {
user.should.have.property(property);
user[property].should.be.a(typeof pureUser[property]);
});
}
});
pureUser is something like this:
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
User variable is defined elsewhere via got.js
change your test to be pureUser[property].should.be.an.Array or user[property].should.be.an.Array
forEach
The forEach() method calls a provided function once for each element in an array, in order.
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
Object.keys(pureUser).forEach(property =>{
// since typeof array is an object we need to check this case separately or test will fail with expecting array to be an object
if (Array.isArray(pureUser[property])) {
console.log('Yes, it\'s an Array')
//it(`should have property ${property}, type: array`, function () {
// user.should.have.property(property);
//});
} else {
console.log('No, it\'s not an Array')
//it(`should have property ${property}, type: ${(typeof property)}`, function () {
//user.should.have.property(property);
// user[property].should.be.a(typeof pureUser[property]);
//});
}
});
When you use forEach on pureUser, the parameter will be the objects properties, like username, id, etc
let pureUser = {
username: "JohnDoe123",
id: 1,
categories: [1,2,3,4]
}
Object.keys(pureUser).forEach(property =>{
console.log(property);
});
You can also access the array in your forEach function.
arr.forEach(item, index, arr)

Javascript objects: How do I make the value of a key be another key (not the key's value)?

Is there a way to programmatically set the value of a key to another key? e.g.
export function getObjectForMapStateToProps(state, reducer) {
let stateObject = {};
for (let key in state[reducer]) {
if (state[reducer].hasOwnProperty(key)) {
stateObject[key] = state[reducer][key];
}
}
return stateObject;
}
The goal is for this to return an object where each key, value pair is like so:
namespace: state.city.namespace
What I am actually getting is the VALUE of the state.city.namespace key:
namespace: 'DIskieisSi98s8sjw'.
Thanks in advance for your help!
EDIT -- ADDING ADDITIONAL CONTEXT
#mem035 I probably should have added this context. I am trying create a function that will enable me to stop having to type out the mapStateToProps for Redux. For the above example, here is the map:
const mapStateToProps = state => {
console.log(getObjectForMapStateToProps(state, 'city'));
return {
namespace: state.city.namespace,
componentId: state.city.componentId,
items: state.city.items,
defaultValue: state.city.defaultValue,
selectItem: state.city.selectItem,
allowAdd: state.city.allowAdd,
validationRegEx: state.city.validationRegEx,
regExDescription: state.city.regExDescription,
hasForeignKey: state.city.hasForeignKey,
foreignKeyModel: state.city.foreignKeyModel,
foreignKeyValue: state.city.foreignKeyValue,
errorMessages: state.city.errorMessages,
isError: state.city.isError,
isLoading: state.city.isLoading,
apiRoute: state.city.apiRoute
};
};
When the value becomes a string none of the properties are mapping/working.
Just stringify your result instead of again accessing the object.
Instead of:
stateObject[key] = state[reducer][key];
Use:
stateObject[key] = `state.${reducer}.${key}`;

deep change state with variable index

I'm trying to follow the instructions found in Cleaner/shorter way to update nested state in Redux? [the accepted answer]
The thing is in my particular case, i have a layer that really depends on which model the user has selected up to that point. My structure:
Now in my reducer, i've tried (just want to change the favorite leaf to true):
let newStateForFavorites = {...state, models: {
...state.models,
62416: {
...state.models.62416,
details: {
...state.models.62416.details,
favorited: true
}
}
}};
Javascript complains. If i try to extract it to a var:
const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {...state, models: {
...state.models,
currentModelToFav: {
...state.models.currentModelToFav,
details: {
...state.models.currentModelToFav.details,
favorited: true
}
}
}};
Javascript does not associate the const. And it errors out -currentModelToFav is undefined-
Ideas of what i'm doing wrong? Thanks!
If you want to use a variable as a property name you'll have to use these constructs:
{[variableName] : value}
and
{propertyName : variable[variableName]}
So, your object literal will become:
const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {...state, models: {
...state.models,
[currentModelToFav]: {
...state.models[currentModelToFav],
details: {
...state.models[currentModelToFav].details,
favorited: true
}
}
}};
You need to use bracket notation to pull an object key using a variable:
const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {
...state,
models: {
...state.models,
[currentModelToFav]: {
...state.models[currentModelToFav],
details: {
...state.models[currentModelToFav].details,
favorited: true
}
}
}
};

ES6 destructuring two objects with same property name

i have two javascript object with the next syntax:
let section = { name: "foo", tables: [] }
let field = { name: "bar", properties: {} }
and a function who expect those objects, but in the function i only use the name of each object, so i wanted to know if i can destructuring the two objects in the function's declaration like:
function something( {name}, {name} ) {
//code
}
the first should be section.name and the second should be field.name.
Is there a way two do a destructuring in this scenario? or should i spect only the names in the function?
Which is better?
Thank you.
Yup, it looks like you can label/reassign the parameters: {before<colon>after}
var section = { name: 'foo', tables: [] };
var field = { name: "bar", properties: {} };
function something({ name: sectionName }, { name: fieldName }) {
console.log(sectionName, fieldName);
}
something(section, field);

ES6 deep nested object destructuring

I have an object called this.props which contains
{
actions: Object,
dirty: false,
form: "Statement",
autofill: function(),
**statement: Object**
}
statement contains
{
firstName: "John"
lastName: "Peter"
isConfirmed: true
}
I would like to extract statement object and the isConfirmed property in the same line using es6 destructuring
I've tried
const { statement: isConfirmed, isAdmin } = this.props
which I get an error when I do let a = isConfirmed, b = statement
I would like to extract statement object and the isConfirmed property in the same line
const { statement: { isConfirmed }, statement } = this.props;
That way you get both isConfirmed and the whole statement object.
References:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring

Categories