How can a create another array from my javascript array - javascript

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

Related

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

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.

Is it possible to add additional property to to filtered objects from an array of objects?

I have an object like this :
{
"roleId": "75f6af0f-a483-4ad1-af5f-5802887fe5e6",
"roleClaims": [
{
"type": "Permissions",
"value": "Permissions.Brands.View",
"selected": false
},
{
"type": "Permissions",
"value": "Permissions.Brands.Create",
"selected": false
},
{
"type": "Permissions",
"value": "Permissions.Dashboard.Create",
"selected": false
},
{
"type": "Permissions",
"value": "Permissions.Users.Create",
"selected": false
}
]
}
I want to re-organize the roleClaims array [ like each unique types objects (value = "Permissions.Brands.View" > Brands ) are separated array ] as mentioned below. And additionally add an extra property checkboxId (which value is unique number) to filtered object from the array of objects.
Is is really possible?
{
"roleId": "75f6af0f-a483-4ad1-af5f-5802887fe5e6",
"roleClaims": [
{
"valueId": "a8ca7eac-4f18-42d6-983f-44f6a8e157dc",
"valueType": "Brands",
"valueArray": [
{
"checkboxId": uuidv4(), // create new unique id
"type": "Permissions",
"value": "Permissions.Brands.View",
"selected": false
},
{
"checkboxId": uuidv4(),,
"type": "Permissions",
"value": "Permissions.Brands.Create",
"selected": false
}
]
},
{
"valueId": "a2566fd4-8763-41d4-881e-029851a440fd",
"valueType": "Dashboard",
"valueArray": [
{
"checkboxId": uuidv4(),,
"type": "Permissions",
"value": "Permissions.Dashboard.Create",
"selected": false
}
]
},
{
"valueId": "72328955-2bd2-469c-a094-be0bba383edd",
"valueType": "Users",
"valueArray": [
{
"checkboxId": uuidv4(),,
"type": "Permissions",
"value": "Permissions.Users.Create",
"selected": false
}
]
}
]
}
I tried with this :
const getRoleDetailsByRoleId = roleId => {
axios.get(`${urls.account.permissions.get_all_by_roleId}?roleId=${roleId}`).then(res => {
const permissionData = res.data;
const splitedValues = [];
permissionData.roleClaims.forEach(item => splitedValues.push(item.value.split('.')[1]));
const uniqueValues = [...new Set(splitedValues)];
const modifiePermissiondObj = {
roleId: permissionData.roleId,
roleClaims: uniqueValues.map(item => ({
valueId: uuidv4(),
valueType: item,
valueArray: permissionData.roleClaims.filter((fileredItem, index, arr) => fileredItem.value.split('.')[1] === item)
}))
};
setPermissions(modifiePermissiondObj);
setIsPageLoaded(true);
});
};
I have modified the roleClaims array but can't add the additional property.
If possible please help me.
const permissionData = {
"roleId": "75f6af0f-a483-4ad1-af5f-5802887fe5e6",
"roleClaims": [
{
"type": "Permissions",
"value": "Permissions.Brands.View",
"selected": false
},
{
"type": "Permissions",
"value": "Permissions.Brands.Create",
"selected": false
},
{
"type": "Permissions",
"value": "Permissions.Dashboard.Create",
"selected": false
},
{
"type": "Permissions",
"value": "Permissions.Users.Create",
"selected": false
}
]
}
const transformedPermissionData = permissionData.roleClaims.reduce((newOutput, role) => {
const extractedRole = role.value.split('.')[1];
const roleIndex = newOutput.roleClaims.findIndex(output => output && output.valueType === extractedRole)
if(roleIndex !== -1){
newOutput.roleClaims[roleIndex].valueArray.push({...role, checkboxId: 'UUID'})
}else {
newOutput.roleClaims.push({
valueId: 'UUID',
valueType: extractedRole,
valueArray: [{...role, checkboxId: 'UUID'}]
})
}
return newOutput
}, { roleId: permissionData.roleId, roleClaims: []})
console.log(transformedPermissionData)
You just need to map your valueArray like this:
valueArray: permissionData.roleClaims
.filter((fileredItem, index, arr) => fileredItem.value.split('.')[1] === item)
.map(value => ({...value, checkboxId: uuidv4()}))

Need help formatting array in JavaScript

I have a JavaScript array with the following format:
[
{
"header": true,
"id": "0",
"name": "dairy",
},
{
"category": "dairy",
"header": false,
"id": "-LSlje6ESGALGpckMhb7",
"name": "milk",
},
{
"category": "dairy",
"header": false,
"id": "-LSm9EpFg5DhW036aUle",
"name": "cheese",
},
{
"header": true,
"id": "3",
"name": "dessert",
},
{
"category": "dessert",
"header": false,
"id": "-LSm9MLZkrnvtPySw5U6",
"name": "cake",
},
{
"category": "dessert",
"header": false,
"id": "-LSmAQ0rdDLrpz0TSPuD",
"name": "pie",
},
{
"header": true,
"id": "6",
"name": "fruit",
},
{
"category": "fruit",
"header": false,
"id": "-LSlazVIGAKLakxAIa8G",
"name": "apple",
},
{
"category": "fruit",
"header": false,
"id": "-LSlb5GH6xZz-DpNVS22",
"name": "pear",
},
{
"category": "fruit",
"header": false,
"id": "-LSwWJldY1nxQrotyv-V",
"name": "strawberry",
},
{
"header": true,
"id": "10",
"name": "meat",
},
{
"category": "meat",
"header": false,
"id": "-LSljXQzfXthJbOA54Ah",
"name": "fish",
},
{
"category": "meat",
"header": false,
"id": "-LSmA2-R9pOY8abAUyST",
"name": "steak",
},
{
"category": "meat",
"header": false,
"id": "-LSmAJ4J4gIfVQ8sgPDa",
"name": "pork",
},
]
What I am trying to do, is map through this array, and transform it to the following format:
[
{
title: nameOfFirstHeader,
data: items.slice(indexOfFirstHeader, indexOfSecondHeader),
},
{
title: nameOfSecondHeader,
data: items.slice(indexOfSecondHeader, indexOfThirdHeader),
},
{
title: nameOfThirdHeader,
data: items.slice(indexOfThirdHeader, indexOfFourthHeader),
},...and so on
]
So basically there will be an object section for each 'header' that is found in the original array. Each object section data property will contain the items found between the first header and the second header, and so on, until there are no more headers. I really can't wrap my head around how I can do this. Here is a reference to the the module I am using: https://github.com/saleel/react-native-super-grid#sectiongrid-example
Thanks!
I think this may be what you're trying to accomplish...
var grouped = items.reduce((acc,obj)=>{
let {header, name} = obj;
if (header) return [...acc, { title:name, data:[] }] // either first matching header or new match. Add fresh 'header' object
if (!acc.length) return acc; //not header and none have passed. Do nothing
let allButLast = acc.slice(0, acc.length-1),
lastElem = acc[acc.length-1]; // not a header, but there is an existing match. Add it to last match's data array
return [
...allButLast,
{
...lastElem,
data:[...lastElem.data, obj]
}
]
},[])
but it seems unreliable to trust the order of an array for this purpose. It would probably be more reliable to match by isHeader.name === notHeader.category to be less presumptive about the order of data you're iterating over. Like this...
var grouped = items.reduce((acc,obj)=>{
let {header, name, category} = obj;
if (header) return [...acc, { title:name, data:[] }];
if (!acc.length) return acc;
return acc.map((elem)=>{
if (elem.title !== category) return elem;
return {
...elem,
data: [ ...elem.data, obj]
};
})
},[])
I think you can probably do something like
const data = [];
let activeIndexForData = -1;
for(let i = 0; i < dataToSort.length -1; i++) {
if(dataToSort[i].header) {
activeIndexForData++;
}
if(data.length < activeIndexForData - 1) {
data.push({ title: dataToSort[i].name, data# []})
}
else {
data[activeIndexForData].data.push({ title: dataToSort[i].name, data: [])
}
}

Compare two arrays of objects and filter results

Example:
const depositAddress = '2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG';
DBarray1.forEach( (tx) => {
console.log(tx);
})
TXarray2.forEach( (sim) => {
console.log(sim);
});
DBarray1 = [
{
"_id": "575e2b7875a402111900ba8f",
"username": "aleluia#gmail.com",
"playerWallet": "2NFt8YfydBU5JD9U8Xq2ucbfUp2sP7BjUrh",
"User_Profile": {
"TXHash": [
"7fbe28f75412f19dfd123a08ce03c33c302aa13d1e68d38ab8cb4c7418777f8e"
]
}
},
{
"_id": "575e2946b909906a17ea65b9",
"username": "super#user.com",
"playerWallet": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"User_Profile": {
"TXHash": [
"cf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b",
"6219def49d2e8284a6031f4c7e05e21adf756d38904e6359bd7844ae14c75a50"
]
}
}
] // end console.log(DBarray1);
TXarray2 = [
{
"id": "cf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b",
"normalizedHash": "f62af1a61c7eb569c1a171ad23c70bc218bd7244c9c5c92cf7d98638314fbbc5",
"date": "2016-06-21T04:11:18.541Z",
"fee": 6280,
"inputs": [
{
"previousHash": "2660fb761354671912b0cea6427e9ee91a98a507e5f1408865a6058b566b508c",
"previousOutputIndex": 0
},
{
"previousHash": "ce3ef138c11ea4d1766cce52ccf5f1e91790bc03b56561b0eb669041bae4e1a3",
"previousOutputIndex": 0
}
],
"outputs": [
{
"vout": 0,
"account": "2N92kApgroS6CTVuTajtjWtpcAZpUiyQoDT",
"value": 861003
},
{
"vout": 1,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 3100000,
"isMine": true,
"chain": 0,
"chainIndex": 0
}
],
"entries": [
{
"account": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"value": -3967283
},
{
"account": "2N92kApgroS6CTVuTajtjWtpcAZpUiyQoDT",
"value": 861003
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 3100000
}
],
"confirmations": 70,
"pending": false,
"instant": true,
"instantId": "5768be65427689eb06e597559c7e6cf0",
"blockhash": "00000000002d9fb51c7c3c1607fe062eff686aa6be657a59fee6c3044963897d",
"height": 872152
},
{
"id": "6219def49d2e8284a6031f4c7e05e21adf756d38904e6359bd7844ae14c75a50",
"normalizedHash": "179a4466fdfc5470e99e43aa177d43aa4f09e3a06760fd5bebffdda080d4407f",
"date": "2016-06-21T04:13:23.650Z",
"fee": 9096,
"inputs": [
{
"previousHash": "5d2879a79ea3d0dcb50049ef9ca46ef7e8d82caf2073a299a6cd0332add404c8",
"previousOutputIndex": 1
},
{
"previousHash": "d75288e69a3fc2edd534ddcd845af6a280a27af58013ae82828c8a8f813829c1",
"previousOutputIndex": 0
},
{
"previousHash": "eea4f9b274708b60c1b030203543a155857bc54aa11055ada04aceee706f96b9",
"previousOutputIndex": 0
}
],
"outputs": [
{
"vout": 0,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 2000000,
"isMine": true,
"chain": 0,
"chainIndex": 0
},
{
"vout": 1,
"account": "2MzFTm5jnCDiAapjNnyVgZAJrXMKfQ74esV",
"value": 9859
}
],
"entries": [
{
"account": "2MzcwVFKF274bMNT5tNEDY7Ua7bAgvFUdu9",
"value": -35316
},
{
"account": "2MzFTm5jnCDiAapjNnyVgZAJrXMKfQ74esV",
"value": 9859
},
{
"account": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"value": -1983639
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 2000000
}
],
"confirmations": 70,
"pending": false,
"instant": true,
"instantId": "5768bee2b5bdf3f406e7db035aef016a",
"blockhash": "00000000002d9fb51c7c3c1607fe062eff686aa6be657a59fee6c3044963897d",
"height": 872152
},
{
"id": "7fbe28f75412f19dfd123a08ce03c33c302aa13d1e68d38ab8cb4c7418777f8e",
"normalizedHash": "b4f1974dccde5ea9dfb0abcd7d4a6f3f14995d9dd422aa7d2a9078229ff18ff4",
"date": "2016-06-21T03:39:25.034Z",
"fee": 3465,
"inputs": [
{
"previousHash": "97fbb6ed8646f7ce9ed10a4230a70348151d5b6b208ad068e3a1a3fddae2dc0e",
"previousOutputIndex": 2
}
],
"outputs": [
{
"vout": 0,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 111200000,
"isMine": true,
"chain": 0,
"chainIndex": 0
},
{
"vout": 1,
"account": "2NFJnLrhsCDfG3ooQvGC169gnzBabtRgV2y",
"value": 244246993
}
],
"entries": [
{
"account": "2NCGUnwpNgaJbhMZKLJcBrWvZhWnai5PjVC",
"value": -355450458
},
{
"account": "2NFJnLrhsCDfG3ooQvGC169gnzBabtRgV2y",
"value": 244246993
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 111200000
}
],
"confirmations": 77,
"pending": false,
"instant": false,
"blockhash": "0000000000509dbc80cc3d86cdb10ce8e87ab7867c6775a9b00ca904fbe70da7",
"height": 872145
}
]// end console.log(TXarray2);
How can we check if TXarray2.id which is the transactions id, if it matches a payment made by the user inside DBarray1.User_Profile.TXHash for examplecf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b .
I want to know forEach TXarray2.id who made the payment . I tried to do this with promises and i will share some code when i get home but i'm sure it can be done with async for all users one by one and log who made a payment today to this wallet. I tried with array.find() method to check inside TXHash but failed, i don't fully grasp many prototype methods yet...
Hopefully someone already thinks this a walk on the park for him and found a better solution to validate this kind of stuff. I will accept any answer even with lodash, maping, anything. TY !!!
You iterate TXArray2 and do a lookup in DBarray1 for the transactionId.
I like to work with native array methods like map and filter, so I would use something like the following:
const result = TXarray2.map(tx => ({
transaction: tx,
user: DBarray1.filter(user => user.User_Profile.TXHash.indexOf(tx.id) > -1)[0]
}));
In this example result is an array where every element contains a transaction and the matching user.
If you already have all of the transaction and user data, could you do something like this?
// for each transaction in TXarray2
for (let { 'id': transactionId } of TXarray2) {
// check each entry in DBarray1
for (let { '_id': userId, 'User_Profile': { 'TXHash': transactions } } of DBarray1) {
if (transactions.includes(transactionId)) {
console.log(`${transactionId} was made by ${userId}`);
}
}
}
The best way here is to use Array.indexOf (or Array.findIndex if you want to use callbacks) which returns -1 if an entry is not in an array.
Here's the sync variant:
var paid = [];
TXArray2.forEach(function(transaction){
for(var i = 0; i < DBArray1.length; ++i){
if(DBArray1[i].User_Profile.TXHash.indexOf(transaction.id) > -1){
paid.push({
user : DBArray1[i],
transaction : transaction
});
break;
}
}
});
console.log(paid);

issue with getting JSON child values by specifying full path

I have the below JSON response
{
"r": [{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg":[ {
"Name": "james",
"Rate": 0.05
},
{
"Name": "Jack",
"Rate": 0.55
},
{
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
},
{
"Name": "Jack",
"Rate": 0.55
},
{
"Name": "Mcd",
"Rate": 0.01,
}],
},
{
"IsDefault": false,
"re": {
"Name": "Depo"
},
"Valid": "Oct8, 2013",
"Clg": [{
"Name": "james",
"Rate": 0.05
},
{
"Name": "Jack",
"Rate": 0.55
},
{
"Name": "Mcd",
"Rate": 0.01,
}],
}]
}
I am using $.getJSON method to loads JSON data and adding it in collection by checking whether it is array as below . It is working fine as expected.
var res = loadFromJson(result.r);
loadFromJson = function(input) {
if (_.isArray(input)) {
console.log("Inside Array");
var collection = new CompeCollection();
_.each(input, function(modData) {
collection.add(loadFromJson(modData));
console.log("collection length:"+modData.length);
});
return collection;
}
};
But when i try to specify the exact path(r.Clg) of my JSON response it is not even coming to above if condition though it is valid response.
var res = loadFromJson(result.r.Clg);
loadFromJson = function(input) {
if (_.isArray(input)) {
console.log("Inside Array");
var collection = new CompeCollection();
_.each(input, function(modData) {
collection.add(loadFromJson(modData));
console.log("collection length:"+modData.length);
});
return collection;
}
};
What should i do when i need to specify actual or full path?
Can any one tell me what could be the problem when i pass more specific json values?
Thanks in advance.
result.r.Clg doesn't exist. result.r is an array.
If you only wanted to access the first object in the r array, you would do this:
var res = loadFromJson(result.r);
var clg = res[0].Clg;
Or you could loop over all the objects, perhaps capturing all the Clgs in one array:
var clgs = res.map(function (obj) { return obj.Clg; }, []);

Categories