How to check any every array object property empty or not? - javascript

The purpose of function is to get false when all answers are empty. Currently, some how getting **false when only one single answers empty and rest have data inside.
what is the best way to check all answers are empty or not. It doesn't matter some has data and some doesn't. I just wanna see all empty or not.
const questions = [{
"answers": [{
"value": "Browns",
"selected": false,
},
{
"value": "Oranges",
"selected": false,
},
{
"value": "Purples",
"selected": false,
}
],
"info": "",
"type": "DESELECT",
"lastUpdated": "2021-11-01T22:50:28.359"
},
{
"answers": [],
"info": "",
"type": "DESELECT",
"lastUpdated": "2021-11-01T22:50:35.392"
},
{
"answers": [{
"value": "AnimalPrints",
"selected": false,
},
{
"value": "BigLogos",
"selected": true,
},
{
"value": "Floral",
"selected": false,
}
],
"info": "",
"type": "DESELECT",
"lastUpdated": "2021-11-01T22:50:43.883"
}
];
console.clear();
console.log("------------ES6------------");
const es6Result = questions.every((item) => !_.isEmpty(item.answers));
console.log(es6Result);
const lodashResult = _.every(questions, !_.isEmpty('answers'));
console.log("------------Lodash------------");
console.log(lodashResult);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>

You could use .some(), you will get true if at least 1 answers is not empty, and you will get false if all answers are empty
const es6Result = questions.some((item) => item.answers.length);

I think the logic you describe requires:
const lodashResult = !_.every(questions, _.isEmpty('answers'));
or
const es6Result = !questions.every((item) => _.isEmpty(item.answers));

const questions = [{
"answers": [{
"value": "Browns",
"selected": false,
},
{
"value": "Oranges",
"selected": false,
},
{
"value": "Purples",
"selected": false,
}
],
"info": "",
"type": "DESELECT",
"lastUpdated": "2021-11-01T22:50:28.359"
},
{
"answers": [],
"info": "",
"type": "DESELECT",
"lastUpdated": "2021-11-01T22:50:35.392"
},
{
"answers": [{
"value": "AnimalPrints",
"selected": false,
},
{
"value": "BigLogos",
"selected": true,
},
{
"value": "Floral",
"selected": false,
}
],
"info": "",
"type": "DESELECT",
"lastUpdated": "2021-11-01T22:50:43.883"
}
];
console.clear();
console.log("------------ES6------------");
const es6Result = questions.map((item) => _.isEmpty(item.answers)).indexOf(true) > -1;
console.log(es6Result);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>

There's not really a need for lodash here. You should be able to accomplish what you want by using Array.prototype.every
questions.every((item) => item.answers.length > 0)
This will always return true, as long as all 'answers' array have one or more items inside, else false.
As Georgy said, you can use Array.prototype.some when you want to check for at least one of the items.

Related

How do I update nested object by ID in VueJS

Issue:
I'm trying to update(axios.patch) active data from false to true of a nested object (children) by ID using axios patch request. I'm using vuejs as my frontend and json-server as my backend. Can anyone please help me.
Data:
{
"id": 3,
"icon": "store",
"name": "Store Management",
"children": [
{
"id": 1,
"name": "Tables",
"icon": "",
"active": false,
"path": "/store-management/tables"
},
{
"id": 2,
"name": "Discounts",
"icon": "",
"active": false,
"path": "/store-management/discounts"
},
{
"id": 3,
"name": "Surcharges",
"icon": "",
"active": false,
"path": "/store-management/surcharges"
},
{
"id": 4,
"name": "Promos",
"icon": "",
"active": false,
"path": "/store-management/promos"
}
],
"expanded": true,
"path": "",
"active": false,
"hasChildren": true
}
Function:
When I call the #click function the navigateChildren will execute and it needs to get the path of the nested object and at the same time update the active value to true or false.
async navigateChildren(id) {
try {
const menuChildren = await axios.get('http://localhost:3000/menu/3')
const menuChildrenList = menuChildren.data
const children = menuChildrenList.children[id - 1]
const inactive = await axios.patch(
'http://localhost:3000/menu/' + this.menuId,
{
active: false
}
)
console.log(inactive)
const active = await axios.patch('http://localhost:3000/menu/3', {
children: {
active: true
}
})
console.log(active)
const path = children.path
this.$store.commit('setMenuId', id)
this.$router.push(path)
console.log(children)
} catch (error) {
}
}
Many Thanks.

How can a create another array from my javascript array

I'm working with an array from an api call, which I would like to rearrange for something else.
payload = [
{
"id": rexiy,
"orderLabel": "PREP",
"balance": 1900,
"virtual": false,
"type": "credit",
},
{
"id": erptq,
"orderLabel": "PREP",
"balance": 500,
"virtual": true,
"type": "debit"
}
]
I'm trying to create a new array that would have this format
array = [
{
rexiy:1900
},
{
erptq:500
}
]
How do I go about it
You can use object destructuring and map to do this:
const payload = [{
"id": "rexiy",
"orderLabel": "PREP",
"balance": 1900,
"virtual": false,
"type": "credit",
},
{
"id": "erptq",
"orderLabel": "PREP",
"balance": 500,
"virtual": true,
"type": "debit"
}
]
const result = payload.map(({id, balance}) => ({
[id]: balance
}));
console.log(result);

Dynamic values not setting in nested array

I am trying to change the values of my nested object by using the data from another object but for some reason it is never setting the value. If i put static text in there it works but just doesn't work if the data from my other object
const projectFormTypes = [
{
"type": "Theatrical",
"sections" : {
"project": {
"fields": [
{
"label": "Project Title",
"name": "title",
"required": true,
"type": "textbox",
"visible": true,
'value': ''
},
]
},
"participants": {
"fields": [
{
"label": "First Name",
"name": "firstName",
"required": false,
"type": "textbox",
"visible": true,
"value": "first name 1"
},
]
},
"earnings": {
"fields": [
{
"label": "Compensation Amount",
"name": "wages",
"prefix": "$",
"required": false,
"type": "textbox",
"visible": true,
"value": 100000
},
]
}
}
},
]
const projectData = [{"fileDetailRecordId":3,"detailRecordId":"341697P3","signatoryName":"comp 2","signatoryId":"comp sag","contract":"Theatrical","sagId":"aftra 2","title":"Project 2","principalPhotoDate":"2019-12-13","madeFor":"Interactive Media","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"In-Flight","commercialTitle":"Project 2","sessionDate":"2019-12-13","useType":"Clip Use","ssn":"987654","firstName":"test","middleName":"test","lastName":"test","loanOutNumber":"45687","loanOutName":"54854","performerType":"Background","performerCategory":"Dancer","paymentType":"Payroll","wages":"852963","subjectToPh":"852963","phContrib":"8529363","contribPercent":"10.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"},{"fileDetailRecordId":1,"detailRecordId":"341697P1","signatoryName":"comp name","signatoryId":"comp aftra","contract":"Theatrical","sagId":"aftra id","title":"Project 1","principalPhotoDate":"2019-12-13","madeFor":"Foreign TV","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"Network","commercialTitle":"Project 1","sessionDate":"2019-12-13","useType":"Phono Conversation","ssn":"456","firstName":"first name 1","middleName":"middle name 1","lastName":"last name 1","loanOutNumber":"456","loanOutName":"456","performerType":"AFTRA Staff","performerCategory":"Actor","paymentType":"Deferred","wages":"500","subjectToPh":"500","phContrib":"500","contribPercent":"1000.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"},{"fileDetailRecordId":2,"detailRecordId":"341697P2","signatoryName":"comp name","signatoryId":"comp aftra","contract":"Theatrical","sagId":"aftra id","title":"Project 1","principalPhotoDate":"2019-12-13","madeFor":"Foreign TV","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"Home Video","commercialTitle":"Project 1","sessionDate":"2019-12-13","useType":"Clip Use","ssn":"123","firstName":"last name 2","middleName":"last name 2","lastName":"last name 2","loanOutNumber":"456","loanOutName":"456","performerType":"AFTRA Staff","performerCategory":"Dance Coreographer","paymentType":"Deferred","wages":"800","subjectToPh":"800","phContrib":"800","contribPercent":"50.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"}]
const pp = Object.keys(projectFormTypes).forEach(function(r) {
for(let key in projectFormTypes[r].sections){
for(let o in projectFormTypes[r].sections[key].fields){
projectFormTypes[r].sections[key].fields[o].value = projectData[0][o.name];
}
}
});
console.log('result', projectFormTypes);
projectData[0][o.name]
should be
projectData[0][projectFormTypes[r].sections[key].fields[o].name]
o is the index in the fields array, and numbers don't have a name property. You want the name of the current element of the for loop.
But the code is simplified and less error prone if you use forEach() for all the nested loops.
const projectFormTypes = [{
"type": "Theatrical",
"sections": {
"project": {
"fields": [{
"label": "Project Title",
"name": "title",
"required": true,
"type": "textbox",
"visible": true,
'value': ''
}, ]
},
"participants": {
"fields": [{
"label": "First Name",
"name": "firstName",
"required": false,
"type": "textbox",
"visible": true,
"value": "first name 1"
}, ]
},
"earnings": {
"fields": [{
"label": "Compensation Amount",
"name": "wages",
"prefix": "$",
"required": false,
"type": "textbox",
"visible": true,
"value": 100000
}, ]
}
}
}, ]
const projectData = [{"fileDetailRecordId":3,"detailRecordId":"341697P3","signatoryName":"comp 2","signatoryId":"comp sag","contract":"Theatrical","sagId":"aftra 2","title":"Project 2","principalPhotoDate":"2019-12-13","madeFor":"Interactive Media","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"In-Flight","commercialTitle":"Project 2","sessionDate":"2019-12-13","useType":"Clip Use","ssn":"987654","firstName":"test","middleName":"test","lastName":"test","loanOutNumber":"45687","loanOutName":"54854","performerType":"Background","performerCategory":"Dancer","paymentType":"Payroll","wages":"852963","subjectToPh":"852963","phContrib":"8529363","contribPercent":"10.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"},{"fileDetailRecordId":1,"detailRecordId":"341697P1","signatoryName":"comp name","signatoryId":"comp aftra","contract":"Theatrical","sagId":"aftra id","title":"Project 1","principalPhotoDate":"2019-12-13","madeFor":"Foreign TV","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"Network","commercialTitle":"Project 1","sessionDate":"2019-12-13","useType":"Phono Conversation","ssn":"456","firstName":"first name 1","middleName":"middle name 1","lastName":"last name 1","loanOutNumber":"456","loanOutName":"456","performerType":"AFTRA Staff","performerCategory":"Actor","paymentType":"Deferred","wages":"500","subjectToPh":"500","phContrib":"500","contribPercent":"1000.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"},{"fileDetailRecordId":2,"detailRecordId":"341697P2","signatoryName":"comp name","signatoryId":"comp aftra","contract":"Theatrical","sagId":"aftra id","title":"Project 1","principalPhotoDate":"2019-12-13","madeFor":"Foreign TV","ppe":"2019-12-13","sessionDateTv":"2019-12-13","marketPaid":"Home Video","commercialTitle":"Project 1","sessionDate":"2019-12-13","useType":"Clip Use","ssn":"123","firstName":"last name 2","middleName":"last name 2","lastName":"last name 2","loanOutNumber":"456","loanOutName":"456","performerType":"AFTRA Staff","performerCategory":"Dance Coreographer","paymentType":"Deferred","wages":"800","subjectToPh":"800","phContrib":"800","contribPercent":"50.0000","detailStatus":"DRAFT","earningsFileId":341697,"detailStatusId":{"parentRefId":32,"activeFlag":true,"refCode":"detail_processing","refValue":"Processing","comments":"detail is being processed","createdBy":"NS","createdAt":"2018-10-04T01:33:18.000+0000","updatedBy":"NS","updatedAt":"2019-06-19T17:45:39.000+0000","cmsProcessEfDetailLogList":[],"referenceId":33,"cmsEarningsFileList":[],"cmsEarningsFileList1":[]},"createdBy":"UI","updatedBy":"UI"}]
projectFormTypes.forEach(function(type) {
Object.values(type.sections).forEach(function(section) {
section.fields.forEach(function(field) {
field.value = projectData[0][field.name];
});
});
});
console.log('result', projectFormTypes);

How to filter nested array using Lodash?

This is my Array (http://www.jsoneditoronline.org/?id=cc51a12581667055781639b586fa6e15):
[
{
"documents": [
{
"name": "a",
"isSelected": true,
"status": "good"
},
{
"name": "b",
"isSelected": false,
"status": "good"
}
]
},
{
"documents": [
{
"name": "a",
"isSelected": true,
"status": "bad"
},
{
"name": "b",
"isSelected": false,
"status": "good"
}
]
},
{
"documents": [
{
"name": "a",
"isSelected": true,
"status": "verygood"
},
{
"name": "b",
"isSelected": false,
"status": "good"
}
]
},
{
"documents": [
{
"name": "a",
"isSelected": false,
"status": "good"
},
{
"name": "b",
"isSelected": false,
"status": "good"
}
]
}
]
I need to write condition using _.lodash.
This condition has to return TRUE if in array is at least one Selected document with Status other than good or verygood
Based on array from above.
http://prnt.sc/de3gx9
You can see on the screenshot that in array is an object with:
isSelected
Has other status than good or verygood
If in my Array is at least one object (with isSelected = true, and status = bad (or any other than good or verygood).
Then I want to see RESULT: TRUE
function checkStatusInArray() {
var data = [....]; // this is my array
var isDocumentSelectedWithWrongStatus = _.some(data, { isSelected: true, status: !"good" || !"verygood" });
// So if in array are some items with isSelected = true and status != good || verygood, then isDocumentSelectedWithWrongStatus = TRUE
return isDocumentSelectedWithWrongStatus;
}
You can do it without lodash - Array#some inside Array#some and a predicate (the predicate can be inlined as anonymous function), if the predicate returns, the result will be truthy:
function checkData(data, predicate) {
return data.some(function(item) {
return item.documents.some(predicate);
});
}
function predicate(document) {
return document.isSelected &&
!(document.status === 'good' ||
document.status === 'verygood');
}
function checkData(data, predicate) {
return data.some(function(item) {
return item.documents.some(predicate);
});
}
function predicate(document) {
return document.isSelected &&
!(document.status === 'good' ||
document.status === 'verygood');
}
var data = [{
"documents": [{
"name": "a",
"isSelected": true,
"status": "good"
}, {
"name": "b",
"isSelected": false,
"status": "good"
}]
}, {
"documents": [{
"name": "a",
"isSelected": true,
"status": "bad"
}, {
"name": "b",
"isSelected": false,
"status": "good"
}]
}, {
"documents": [{
"name": "a",
"isSelected": true,
"status": "verygood"
}, {
"name": "b",
"isSelected": false,
"status": "good"
}]
}, {
"documents": [{
"name": "a",
"isSelected": false,
"status": "good"
}, {
"name": "b",
"isSelected": false,
"status": "good"
}]
}];
var result = checkData(data, predicate);
console.log(result);
You could use lodash's flatMap to pluck the documents into one collection and then use some on the collection:
var data = [{"documents":[{"name":"a","isSelected":true,"status":"good"},{"name":"b","isSelected":false,"status":"good"}]},{"documents":[{"name":"a","isSelected":true,"status":"bad"},{"name":"b","isSelected":false,"status":"good"}]},{"documents":[{"name":"a","isSelected":true,"status":"verygood"},{"name":"b","isSelected":false,"status":"good"}]},{"documents":[{"name":"a","isSelected":false,"status":"good"},{"name":"b","isSelected":false,"status":"good"}]}]
var selectedButNotGood = function(document){
return document.isSelected &&
document.status != "good" &&
document.status != "verygood"
}
var result = _.chain(data)
.flatMap('documents')
.some(selectedButNotGood)
.value();
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
You can loop over them and create your own custom array.
var d = [{"documents":[{"name":"a","isSelected":true,"status":"good"},{"name":"b","isSelected":false,"status":"good"}]},{"documents":[{"name":"a","isSelected":true,"status":"bad"},{"name":"b","isSelected":false,"status":"good"}]},{"documents":[{"name":"a","isSelected":true,"status":"verygood"},{"name":"b","isSelected":false,"status":"good"}]},{"documents":[{"name":"a","isSelected":false,"status":"good"},{"name":"b","isSelected":false,"status":"good"}]}]
var statusList = ['good', 'verygood']
var r = d.some(function(o) {
return o.documents.filter(x => !statusList.includes(x.status) && x.isSelected).length > 0;
});
console.log(r)

Knockout set observable array in array

I have a small question about knockout.
I have made a viewmodel
that looks like this (there are more subitems then Actions)
{
"PlatformSettings": [
{
"Actions": [
{
"Selected": false,
"Text": "None",
"Value": "None"
},
{
"Selected": true,
"Text": "Validation1",
"Value": "Validation1"
},
{
"Selected": true,
"Text": "Validation2",
"Value": "Validation2"
},
{
"Selected": true,
"Text": "Validation3",
"Value": "Validation3"
}
],
"Platform": {
"Id": "89",
"Description": "ONTWIKKELB"
}
},{
"Actions": [
{
"Selected": false,
"Text": "None",
"Value": "None"
},
{
"Selected": true,
"Text": "Validation1",
"Value": "Validation1"
},
{
"Selected": true,
"Text": "Validation2",
"Value": "Validation2"
},
{
"Selected": true,
"Text": "Validation3",
"Value": "Validation3"
}
],
"Platform": {
"Id": "89",
"Description": "ONTWIKKELB"
}
}
It works fine, but when i edit the checkboxes in my view and map them
self.Save = function(validate) {
var unmapped = ko.mapping.toJSON(self);
******
return false;
};
unmapped doesn't show the changes. And all the select values still show as on page load. I tried to make observable arrays, but the past 2 hours, but i can't figure it out.
Many thanks
Making the array observable will notify subscribers on add\remove. Making the "selected" property of each element observable will notify subscribers when it changes and allow 2 way binding.
So basically, make the selected property of each array element an observable too.

Categories