Apply function over values whose keys match in another array - arrays

I have a form.value as below
form.value = {
"to_date": "2019-03-21T05:00:00.000Z",
"from_date": "2019-03-13T05:00:00.000Z",
"is_form": ""
"errors":""
}
I have an array as below
filterArray = [
"from_date",
"to_date"
]
I want to iterate over the form.value object keys and apply a function ( converFormat()) over the value of the keys that match in the filter array
as shown below
form.value = {
"to_date": "2019-03-21T05:00:00.000Z", // apply a function() over value since key is present in the filterArray
"from_date": "2019-03-13T05:00:00.000Z", // apply a function() over value since key is present in the filterArray
"is_form": ""
"errors":""
}

Object.keys(form.value).filter(key => filterArray.includes(key)).forEach(key => {
form.value[key] = myFunction(form.value[key])
})
// Or if you want to cache the value in some other variable
const customFormValue = {
...form.value,
...Object.keys(form.value)
.filter(key => filterArray.includes(key))
.reduce(
(pr, curr) => ({
...pr,
[curr]: myFunction(form.value[curr])
}),
{}
)
};

Related

How to get array after convert by reduce()

How to get an array after converted by reduce()?
Before convert:
After convert:
newProductsDetail = newProductsDetail.reduce((acc, curr) => {
const { categoryName } = curr
if (!acc[categoryName]) {
acc[categoryName] = []
}
acc[categoryName].push(curr)
return acc
}, [])
I would like get newProductsDetail[categoryName]
Have any way to approach this?
Thanks to all of you!
you can filter it like this
productDetail.filter( detail => { if(detail !== undefined && detail[0] !== undefined) return detail[0].categoryName === myCategory; return false; } )
Set initial value as object and not list as follows if you want to get hold of value from newProductsDetail[categoryName]:
newProductsDetail = newProductsDetail.reduce((acc, curr) => {
const { categoryName } = curr
if (!acc[categoryName]) {
acc[categoryName] = []
}
acc[categoryName].push(curr)
return acc
}, {}) // dictionary/object is initial and not list
If you only want array and some manipulation, try to use map to iterate and convert final output to array of something.

How to return this local variable in nested functions and "globalize" it?

I am trying to catch some values from a file and put them in an array.
After battling up with conversions and values, I reach my "final" data to return which in my case is arrayFile.I understand that I have nested some functions and now I couldn't return my data properly and globally in the first part of the code, because it displays/returned undefined.
In a few words,how I can retutn this variable specifically or in another variable? Because the console.log works, however just in that block. How could I end my 1st FOR loop and keep the data (arrayFile) global so for being used in other stuff? Any help wuold be precious. Hoping I'm asking questions the right way, thanks for your patience.
const directoryPath = path.join(__dirname, './sample');
//passing directoryPath and callback function
fs.readdir(directoryPath, function (err, files) {
//handling error
if (err) {
return console.log('Unable to scan directory: ' + err);
}
//listing all files using forEach
files.forEach(function (file) {
arrayNomi.push(file);
});
for(i=0;i<arrayNomi.length;i++){
leggiFile(arrayNomi[i],arrayDati)
}
});
function leggiFile(nomeFile,arrayFile){
const xmlFile = fs.readFile(nomeFile,{encoding:'utf8', flag:'r'},
function(err, data) {
if(err)
console.log(err);
else
convert.parseString(data, (err, result) => {
if(err) {
throw err;
}
// `result` is a JavaScript object
// convert it to a JSON string
//const json = JSON.stringify(result, null, 4);
//console.log(json)
// log JSON string
//console.log(json);
// method to collect string values
const collectAllValues = (arr, res = []) => {
// append result "res" with any "string" elt in array "arr"
const r = [
...res,
...(
arr?.filter(
elt => typeof elt !== 'object'
) ?? []
)
];
// filter out "arr" elements that are "objects"
const nx = arr?.filter(
elt => typeof elt === 'object'
) ?? [];
// if "objects" exist in "arr" elements-list
// use ".reduce()" to iterate over the filtered "arr"
// then, for each object, use ".reduce()" to
// iterate over values that are arrays and make
// recursive call to this method & return the value
if (nx && nx.length) {
return (
nx.reduce(
(acc, ob) => ([
...acc,
Object.values(ob)
.filter(v => v && Array.isArray(v))
.reduce((ac2, ar) => ([...ac2, ...collectAllValues(ar)]), acc)
.flat()
]),
r
)
);
} else return r;
// if no "objects" exist, simply return earlier
// result "r"
};
console.log(
'collect all values:\n',
Object.values(result["p:FatturaElettronica"])
.filter(v => v && Array.isArray(v))
.reduce((acc, ar) => ([...acc, ...collectAllValues(ar)]), [])
.flat()
);
var jsonDatiTabella = {};
var dati = [];
jsonDatiTabella.dati = dati;
var tipoDocumento= result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].TipoDocumento[0];
var dataDocumento= result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].Data[0];
var importo = result["p:FatturaElettronica"].FatturaElettronicaBody[0].DatiGenerali[0].DatiGeneraliDocumento[0].ImportoTotaleDocumento[0];
var prestatore= result["p:FatturaElettronica"].FatturaElettronicaHeader[0].CedentePrestatore[0].DatiAnagrafici[0].Anagrafica[0].Denominazione[0];
var committente= result["p:FatturaElettronica"].FatturaElettronicaHeader[0].CessionarioCommittente[0].DatiAnagrafici[0].Anagrafica[0].Nome[0];
var tempDati = {
"TipoDoc": tipoDocumento,
"DataDoc": dataDocumento,
"Importo":importo,
"CedentePrestatore" :prestatore,
"CessionarioCommittente":committente
}
jsonDatiTabella.dati.push(tempDati);
console.log(jsonDatiTabella);
arrayFile.push(tempDati.TipoDoc,tempDati.DataDoc,tempDati.Importo,tempDati.CedentePrestatore,tempDati.CessionarioCommittente)
console.log("arrayFile:" + arrayFile)
});
});
}

ANGULAR Components array key in result get value by id

this.crudService.get('user.php?mode=test')
.subscribe((data:any) => {
{ for (var key in data) { this[key] = data[key]; } };
}
);
This use to work on angular 7 now on angular 13 i get this error (look image)
In template i was using the values for example in json string was and array and i had users, in template was {{users}} , {{posts}} etc.. now the this[key] give error , please help me out its very important can't find solution
i'll show an example code, and then applied to your code:
Example
// creating global variables to receive the values
users: any = null;
posts: any = null;
// simulating the data you will receive
data: any[] = [
{users: ['user1', 'user2', 'user3']},
{posts: ['post1', 'post2', 'post3']}
];
getCrudService() {
// access each object of the array
this.data.forEach(obj => {
// getting keys name and doing something with it
Object.keys(obj).forEach(key => {
// accessing global variable and setting array value by key name
this[String(key)] = obj[String(key)]
})
})
}
Apllied to your code
this.crudService.get('user.php?mode=test').subscribe((data:any) => {
data.forEach(obj => {
Object.keys(obj).forEach(key => {
this[String(key)] = obj[String(key)]
});
});
});
I hope it helped you, if you need help, just reply me.

react check array values based on specific keys returning true/false if values found

I am trying to figure out how to do this but can't seem to wrap my head around it..
I have an address object
const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"123 Any Street",
"addressLine2":"",
"city":"Any Town",
"state":"Indiana",
"state_code":"IN",
"zip":"46220-4466",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":"MyCounty"
}
I want to check for any key that has a value but only specific keys
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
I want to check all keys in objProps against my address object and if any one of them contains a value return true (doesn't matter if its 1 or all 6).. If all keys don't contain a value then return false (Sometimes I will get an address object that has all null values)
I've tried various ways to accomplish this but have failed in each one.
The variation I am working on now is using reduce. While it doesn't meet my needs I thought I could check the resulting array and if length was greater than 0 than I have my answer..
Work-in-progress:
function hasAddressData(obj: any) {
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const keysWithData = objProps.reduce((accumulator, key) => {
const propExistsOnObj = obj.hasOwnProperty(key);
let keyHasData = [];
if (obj[key].length > 0 ) {
keyHasData = obj[key]
}
if (!propExistsOnObj) {
accumulator.push(key);
} else if (keyHasData) {
const equalValueKeyIndex = accumulator.indexOf(key);
accumulator.splice(equalValueKeyIndex, 1);
}
return accumulator;
});
return keysWithData;
}
The above is messed up I know and doesn't work.. Just learning this stuff.. anyone have a suggestion or comment?
Check that .some of the objProps, when looked up on the obj, contain a value. (Either with Boolean or by comparing against '')
const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"123 Any Street",
"addressLine2":"",
"city":"Any Town",
"state":"Indiana",
"state_code":"IN",
"zip":"46220-4466",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":"MyCounty"
}
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const somePopulated = objProps.some(prop => obj[prop]);
// or prop => obj[prop] !== ''
console.log(somePopulated);
const obj = {
"address_type":"Home",
"country":"US",
"addressLine1":"",
"addressLine2":"",
"city":"",
"state":"Indiana",
"state_code":"",
"zip":"",
"phone":"6715551313",
"mobile_number":"",
"extn":"",
"fax":"",
"county_name":""
}
const objProps = ["addressLine1","addressLine2","city","state_code","zip","county_name"];
const somePopulated = objProps.some(prop => obj[prop]);
// or prop => obj[prop] !== ''
console.log(somePopulated);
function checkKeys(target, props) {
return props.some((prop) => {
return target.hasOwnProperty(prop) && target[prop];
});
}
Explanation: some iterates through the props you want to check, returning true immediately when one is found (i.e. the callback returns true). If no props are found (i.e. no callback returns true), some returns false.
hasOwnProperty ensures that you are only checking properties on target, and not looking up the prototype chain. target[prop] checks for a truthy value. You may need to modify this last check if you're going to be handling values other than strings.

Can I update various items in an Immutable List in a React/Redux App

On submitting a form with some updated values, I need to update the state to reflect these changes, but I am new to Immutable.js and am unsure how to do so.
Is it possible to pass a function as a 2nd argument to set or update to update values based on certain criteria.
I have a function which receives state and an array of objects called values. The data in values looks like this:
[
{
key: 'name',
value: 'fred'
},
{
key: 'height',
value: '201'
},
{
key: 'weight',
value: '78'
}
]
I need to map over this data, and the state list, and update the corresponding values in the state list with the values array.
How can I do this. I have put together a function which the Reducer calls to update the state with the new data, but unsure exactly how to get the end result
function updateValue(state, values = []) {
const items = state.get('items').map((i) => {
const key = i.get('key');
values.map(v => {
if (v.key === key) {
return state.update('value', v.value);
}
})
});
return state.update('items', /* Can I use a function here to replace the code above.. to update all of the items in the state List that correspond to the items in the measurements array (which have new values) */);
}
Thank you very much.
Update
Tried the following, but getting the error: Expected [K, V] tuple: i
function updateValue(state, values = []) {
const items = state.get('items').map((i) => {
const key = i.get('key');
values.map(v => {
if (v.key === key) {
return state.update('value', v.value);
}
})
});
return state.update('items', items);
}
More details on the error from Immutable:
function validateEntry(entry) {
if (entry !== Object(entry)) {
throw new TypeError('Expected [K, V] tuple: ' + entry);
}
}
You can use 'merge' to return new object:
return state.merge({
items: values,
});

Resources