My state object is:
[
{
traveller1_dob: '',
traveller1_firstName:'',
traveller1_isPreviousTraveller: false,
traveller1_surname:'',
traveller1_title: ''
},
{
traveller2_dob: '',
traveller2_firstName:'',
traveller2_isPreviousTraveller: false,
traveller2_surname:'',
traveller2_title: ''
}
]
and my payload is:
{key: "traveller1_firstName", value: "ABC", index: 0}
key is the property of the object that needs to be updated
value: is the value we want to update
index: is the index of the traveller in state array
At the moment this is the way I updated:
let obj = state[payload.index];
obj[payload.key] = payload.value;
return _.unionBy(state, [obj], payload.key);
I am aware its not the best way.
Output should be:
[
{
traveller1_dob: '',
traveller1_firstName:'ABC',
traveller1_isPreviousTraveller: false,
traveller1_surname:'',
traveller1_title: ''
},
{
traveller2_dob: '',
traveller2_firstName:'',
traveller2_isPreviousTraveller: false,
traveller2_surname:'',
traveller2_title: ''
}
]
Ideally I want to get rid of index if it's possible.How would you do this?
You're right, you can get rid of the index, and just map over your state and check hasOwnProperty on each stateItem and compare them to the payload.key. The snippet below should solve your problem:
let state = [{
traveller1_dob: '',
traveller1_firstName: '',
traveller1_isPreviousTraveller: false,
traveller1_surname: '',
traveller1_title: ''
}, {
traveller2_dob: '',
traveller2_firstName: '',
traveller2_isPreviousTraveller: false,
traveller2_surname: '',
traveller2_title: ''
}
];
function updateState(payload) {
const updatedState = _.map(state, stateItem => {
if (stateItem.hasOwnProperty(payload.key)) {
stateItem[payload.key] = payload.value;
}
return stateItem;
});
console.log(updatedState);
return updatedState;
}
const samplePayload = {
key: "traveller1_firstName",
value: "ABC",
index: 0
};
updateState(samplePayload);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Related
I'm using external API to make an SQL query for a user. As a result i get matching Entity but as a set of fields, lookin like this:
[
{ IsNull: false, Name: 'Key', Value: '897', Values: null },
{ IsNull: false, Name: 'FirstName', Value: 'User', Values: null },
{ IsNull: false, Name: 'LastName', Value: 'Portal', Values: null },
{
IsNull: false,
Name: 'Email',
Value: 'some#email.com',
Values: null
},
{ IsNull: true, Name: 'Salutation', Value: null, Values: null },
{ IsNull: false, Name: 'Type', Value: '2', Values: null },
{
IsNull: false,
Name: 'LastLoggedDate',
Value: '2022-12-01 15:24:03',
Values: null
}
]
How to transform this response to end with simple object { email: 'some#email', firstName: 'User' lastName: 'Portal' } ??
I ended up with solution like this (below) but i believe there's some easiest way to do that, especially with more fields
let userRawEntity = queryResult.data.Entities[0].Fields;
const userEmail = userRawEntity.filter((obj) => { return obj.Name === 'Email' });
const userFirstName = userRawEntity.filter((obj) => { return obj.Name === 'FirstName' });
const userLastName = userRawEntity.filter((obj) => { return obj.Name === 'LastName' });
return { email: userEmail[0].Value, firstName: userFirstName[0].Value, lastName: userLastName[0].Value };
Edit:
final solution that works and looks nicer. thanks for help :)
if (queryResult.data.TotalEntityCount > 0) {
let user: {[key: string]: string | null } = {}
let userRawEntity = queryResult.data.Entities[0].Fields;
userRawEntity.forEach(data => user[data.Name] = data.Value);
return { email: user.Email, currency: user.Currency } as JwtPayload;
}
As a starting point, I would transform that entire array into an object as follows:
let dataTransformed: {[key: string]: string | null} = {}
data.forEach(d => {
dataTransformed[d.Name] = d.Value
})
Which will give you a nicer looking object as follows:
{
"Key": "897",
"FirstName": "User",
"LastName": "Portal",
"Email": "some#email.com",
"Salutation": null,
"Type": "2",
"LastLoggedDate": "2022-12-01 15:24:03"
}
You now have a familiar object with which to work with. From here, you can strip out the entries you don't want. Note, you may want to do further work in that array transformation such as checking for null values, changing keys to camel case, etc...
Another approach using lodash
_.mapValues(_.keyBy(data, "Name"), o => o.Value || o.Values);
I'm not using the immutable library and I'm working on it.
I want to update the key and value values of mapTable without changing the constant of PRICE_OPTION2_STATE.
I'd appreciate it if you could tell me how.
I have posted the results of the problem and the results I want.
//my code
tableData['option2Price'] = 50000;
const mapCopy = { ...copyState };
let tableCopy = { ...mapCopy[currentTableIndex].mapTable[findTableIndex] };
tableCopy = tableData;
mapCopy.tableCopy = tableCopy;
// problem
console.log(PRICE_OPTION2_STATE);
// initstate
const PRICE_OPTION2_STATE = [
{
id: 1,
option2Name: '',
option2LeftSelect: 'sell',
mapTable: [
{
tableId: 1,
flag: true,
option2Value: '',
option2Price: '',
discountInput2: '',
discountOption2: 'won',
option2Payment: '',
option2Tax: '',
option2settlementAmount: '',
option2RightSelect: 'sell',
},
],
},
];
PRICE_OPTION2_STATE => problem console result
[
{
id: 1,
option2Name: '',
option2LeftSelect: 'sell',
mapTable: [
{
tableId: 1,
flag: true,
option2Value: '',
option2Price: '',
discountInput2: '',
discountOption2: 'won',
option2Payment: '50000',
option2Tax: '',
option2settlementAmount: '',
option2RightSelect: 'sell',
},
],
},
]
result i want
[
{
id: 1,
option2Name: '',
option2LeftSelect: 'sell',
mapTable: [
{
tableId: 1,
flag: true,
option2Value: '',
option2Price: '',
discountInput2: '',
discountOption2: 'won',
option2Payment: '',
option2Tax: '',
option2settlementAmount: '',
option2RightSelect: 'sell',
},
],
},
]
I'll assume copyState is a reference to PRICE_OPTION2_STATE or at least is some sort of (shallow) copy of it. So to copy it, you should:
not use object spread notation at the top level, since it is an array.
not leave it at a shallow copy, but copy it deeply. So you'll also need to map the inner array and copy the objects it has.
Here is some inspiration:
// Assuming copyState has the structure of PRICE_OPTION2_STATE
// Get a deep copy
const mapCopy = copyState.map(({mapTable, ...rest}) => ({
...rest,
mapTable: mapTable.map(obj => ({...obj}))
}));
// Now this assignment will not impact copyState / PRICE_OPTION2_STATE
mapCopy[currentTableIndex].mapTable[findTableIndex] = tableCopy;
I'm trying to pull out a value for a nested object key from some eligibility array that I've got, but I'm getting an undefined value for some reason and need to know what I'm missing.
Given the following array:
const eligibilityCriteria = [
{ field: 'loan.amount', operator: '>=', value: 1000 },
{ field: 'loan.term', operator: '>=', value: 1 },
{ field: 'applicant.birthday', operator: '>=', value: 40 },
{ field: 'applicant.isHomeowner', operator: '==', value: false }
]
I need to find loan.amount from a nested object and pull out it's value:
My big nested object is (coming from the store)
application: {
meta: {
brand: '',
version: '',
affiliate: '',
affiliate_full: '',
campaign: '',
client_hostname: '',
client_href: '',
client_origin: '',
client_useragent: '',
client_ip: '127.0.0.1',
icicle_hash: ''
},
loan: {
amount: 500,
term: null,
purpose: null
}
}
My function right now is:
checkEligibility () {
const eligibilityCriteria = [
{ field: 'loan.amount', operator: '>=', value: 1000 },
{ field: 'loan.term', operator: '>=', value: 1 },
{ field: 'applicant.birthday', operator: '>=', value: 40 },
{ field: 'applicant.isHomeowner', operator: '==', value: false }
]
for (const [index, offer] of this.datasets.offers.entries()) {
const eligibility = eligibilityCriteria
if (eligibility) {
for (const [ci, criteria] of eligibility.entries()) {
// TODO: this fails to pull the value, returns undefined
const field = _.findKey(this.$store.state.application.application, criteria.field)
}
}
}
}
What am I missing?
You must have to misunderstood what _.findKey() does
This method is like _.find except that it returns the key of the first element predicate returns truthy for instead of the element itself.
See Example 2 in the code below.
If you want to retrieve the value from the object at a given path, you must use _.property() (Example 2 below)
const eligibilityCriteria = [
{ field: 'loan.amount', operator: '>=', value: 1000 },
{ field: 'loan.term', operator: '>=', value: 1 },
]
const application = {
loan: {
amount: 500,
term: 2,
amount2: 0,
}
}
// example 1
// outputs "loan"
console.log(_.findKey(application, "amount"))
// outputs undefined - there is no key in application object that has property chain "loan.amount"
console.log(_.findKey(application, "loan.amount"))
// outputs undefined - "amount2" key is there but the value is falsy
console.log(_.findKey(application, "amount2"))
// example 2
for (const [ci, criteria] of eligibilityCriteria.entries()) {
console.log(criteria.field, _.property(criteria.field)(application))
}
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>
I have an object like this:
{
customer: newCustomer.id,
coupon: customer.coupon,
items: [
{
plan: customer.plan
},
]
}
customer.coupon might not always exist, and when it doesn't exist I need it to be null. It can't just be an empty string because that throws an error. I tried coupon: customer.coupon || null but that didn't work.
It's not the cleanest solution, but this works as well:
if (customer.coupon == undefined) {
var nullObject = {
customer: newCustomer.id,
coupon: null,
items: [
{
plan: customer.plan
},
]
}
return nullObject;
} else {
var nonNullObject = {
customer: newCustomer.id,
coupon: customer.coupon,
items: [
{
plan: customer.plan
},
]
}
return nonNullObject;
}
Try this:
{
customer: newCustomer.id,
coupon: customer.coupon || null,
items: [
{
plan: customer.plan
},
]
}
JavaScript has the cool ability to take the last value if all previous values are falsy (That include false, 0, null and others)
So this code:
customer.coupon || null
Will use customer.coupon, but it that value is falsy the it will take the null.
UPDATE
I just saw that you stated that this isn't working, what error are you getting?
let newCustomer = {"id":1};
let customer = {"coupon":null,"plan":1};
var obj = {
customer: newCustomer.id,
coupon: customer.coupon,
items: [
{
plan: customer.plan
},
]
}
console.log(obj);
if(obj.coupon==null)
delete obj["coupon"]
console.log(obj);
and the result from node console I got is
I have the following object in my code:
/* ======= Model ======= */
model = {
workout: [
{
name: '',
email: '',
workouttype: '',
workoutplan: '',
excardio: '',
exstrength: '',
excore: '',
exhiit: '',
validworkout: false,
hasexercises: false
}
]
};
When I try to save the object to localstorage, all the properties are empty.
Here is how I'm storing my object:
saveWorkout: function () {
var key = "Workout",
item = JSON.stringify(model.workout);
localStorage.setItem(key, item);
}
Thanks!