I am trying to filter a JavaScript array (JSON array) with the string array, and set it back in itself.
I am using this code (Removed JSON.stringiFy from allRecords,it was just to show the records on console)
var statusFilters = component.get("v.statusFilters");
console.log('statusFilters--->'+statusFilters);
var allRecords = component.get("v.empWrapperList");
console.log('allRecords--->'+allRecords);
var filteredRecords = allRecords.filter(rec => rec.Status__c == statusFilters);
console.log(filteredRecords);
component.set("v.empWrapperList",filteredRecords);`
Here statusFilter is a string array and allRecords is an object array.
Here are the logs from console.
statusFilters--->Paid
ClaimsDemo.js:119 allRecords--->
[
{
"Id": "a1V2x000001K29pEAC",
"Name": "CL-0000004",
"Member__c": "0032x000004bgAkAAI",
"Date_of_Service__c": "2020-06-25",
"Provider__c": "a112x000003VXGEAA4",
"Status__c": "Void"
},
{
"Id": "a1V2x000001K14OEAS",
"Name": "CL-0000003",
"Member__c": "0032x000004bgAkAAI",
"Billed__c": 22,
"Date_of_Service__c": "2015-09-15",
"Provider__c": "a112x000003VXGEAA4",
"Status__c": "Denied"
},
{
"Id": "a1V2x000001K14JEAS",
"Name": "CL-0000002",
"Member__c": "0032x000004bgAkAAI",
"Billed__c": 22,
"Date_of_Service__c": "2019-10-16",
"Provider__c": "a112x000003VXGEAA4",
"Status__c": "Rejected"
},
{
"Id": "a1V2x000001K14EEAS",
"Name": "CL-0000001",
"Member__c": "0032x000004bgAkAAI",
"Billed__c": 22,
"Date_of_Service__c": "2020-06-04",
"Provider__c": "a112x000003VXGEAA4",
"Status__c": "Paid"
}
]
Actually it is unable to execute this line
var filteredRecords = allRecords.filter(rec => rec.Status__c == statusFilters);
Can you please help.
your first problem is stringifying.filter method is for array.
second problem is that you cant say rec.Status__c === statusFilters statusFiltersis array and Status__c is string. map to array your object array with correct key name and search rec.Status__c in this array. indexOf is a method to find in array
if statusFilters is just array which includes types like
["Void","Denied"]
then
var filteredRecords = allRecords.filter(rec => statusFilters.indexOf(rec.Status__c)>-1);
if statusFilters is an object array like
[ {"Status__c": "Void" }];
then
var filteredRecords = allRecords.filter(rec => ( statusFilters.map(x=>x.Status__c)).indexOf(rec.Status__c)>-1);
Related
I have the following object below with multiple arrays.
{
"services": [
{
"id": "100",
"name": "PIX"
},
{
"id": "200",
"name": "Rendimentos"
}
],
"channels": [
{
"id": "300",
"name": "Chat"
}
]
}
The idea is to generate query strings, something like that.
services=100&services=200&channels=300
I know you can do it with map and join, but I would know if it was with a pure object, now this format below, I'm confused
You can use URLSearchParams() API.
Iterate your data and append key/value pairs or map an entries array to pass to the constructor
I have no idea what determines the expected output you have shown from the data displayed so am using a simpler data structure for demonstration purposes.
You can combine with URL() API to create full url string as shown below also
const data = [
{name:'foo', value:10},
{name:'bar', value:20}
]
// Loop and append key/values
const params = new URLSearchParams();
data.forEach(e => params.append(e.name, e.value));
console.log('params:', params.toString());
// Alternate approach passing entries array to constructor
const params2 = new URLSearchParams(data.map(e => [e.name,e.value]));
console.log('params2:',params2.toString())
//Adding to a URL
const url = new URL('http://example.com')
url.search = params
console.log('Full url:',url)
Using the updated array data in question:
const data={services:[{id:"100",name:"PIX"},{id:"200",name:"Rendimentos"}],channels:[{id:"300",name:"Chat"}]};
const entries = [];
Object.entries(data).forEach(([k,arr])=> arr.forEach(({id}) => entries.push([k,id])));
const params = new URLSearchParams(entries);
const url = new URL('http://example.com')
url.search = params;
console.log(url)
Looks like you're hung up on trying to iterate an object with map() or join(), which you can't do directly. Instead you can use Object.entries to convert the object into an array and iterate that. Since there is a nested map() you can flat() it before join()
let obj = {
"services": [{
"id": "100",
"name": "PIX"
},
{
"id": "200",
"name": "Rendimentos"
}
],
"channels": [{
"id": "300",
"name": "Chat"
}]
}
let queryString = Object.entries(obj).map(s => s[1].map(e => `${s[0]}=${e.id}`)).flat().join('&')
console.log(queryString)
I have the following array with multiple arrays inside the object, how do I generate a query string, where the output should be.
Where services and accountTypes for example that are entries from array it becomes a key in query string.
The value in query string is the id from object in each array
Output should be for example
services=10&services=30&accountTypes=20
Array
[
{
"services": [
{
"id": "10",
"name": "PIX"
},
{
"id": "30",
"name": "Income"
},
],
"accountTypes": [
{
"id": "20",
"name": "Digital Account"
}
]
}
]
My function that I tried.
I tried it with the encodeURIComponent as below, but it's generating undefined
const params = initialFilterDataJson.map((param: QueryParamsType) => {
return encodeURIComponent(param.key) + '=' + encodeURIComponent(param.id)
})
const queryString = params.join('&')
http://localhost:3000/api/accounts?undefined=undefined
Your code is not nesting deep enough in the data structure. You need to have nested loops, first to visit the objects in the outer array, then to visit the keys (with corresponding arrays) of such an object, and then to visit each inner object in such an array:
const initialFilterDataJson = [{"services": [{"id": "10","name": "PIX"},{"id": "30","name": "Income"},],"accountTypes": [{"id": "20","name": "Digital Account"}]}];
const queryString = initialFilterDataJson.flatMap((param) =>
Object.entries(param).flatMap(([key, arr]) =>
arr.map(({id}) => encodeURIComponent(key) + '=' + encodeURIComponent(id))
)
).join('&');
console.log(queryString);
Side note: some web servers can deal better with duplicate keys in the query string when they are suffixed with [], like services[]=10&services[]=20.
I have one react native app the shows some ingredients and the user can select some of it to filter one specific recipe and see all the details, my doubt is, how can I convert the Array of ingredient objects to an Array of "names" and send it via Axios?
Array of objects I am receiving from the API:
Array [
Object {
"id": 8,
"isSelected": true,
"name": "leite condensado",
},
Object {
"id": 9,
"isSelected": true,
"name": "creme de leite",
},
]
and the API expect something like
/report?name='suco de limão', 'bolacha'
So, I need to extract only the values from the name Key, as Array.
Anyone knows if I can do it in the front to keep the API without any update?
You can use the Array.prototype.map() function. Array.prototype.map( ) MDN Documentation
What this does is basically for each element call a callback fn on your current array and returns a new array as per the code you write in the callback fn. What I've done in the below code is to just retrieve the 'name' property of each object from the original array and return those names as a new array.
Then loop over the names array and append to your api URL. I have done both these things in the below code snippet, you can try and run it to understand it better.
const arr = [
{
id: 8,
isSelected: true,
name: 'leite condensado',
},
{
id: 9,
isSelected: true,
name: 'creme de leite',
},
];
const nameArr = arr.map(obj => obj.name);
//logging names array to console
console.log(nameArr);
//appending names to your api url
let url = `/report?name=`;
nameArr.forEach((name, index, ar) => {
index === ar.length - 1 ? (url += ` '${name}'`) : (url += `
'${name}', `);
});
//logging updated API URL to console
console.log(url);
Not sure if I understood the question completely, but maybe you need something like this?
let params = []
const array = [
{
"id": 8,
"isSelected": true,
"name": "leite condensado",
},
{
"id": 9,
"isSelected": true,
"name": "creme de leite",
},
]
array.map(item => params.push(item.name))
console.log(params)
https://codepen.io/pen/?editors=0011
The result would be ["leite condensado", "creme de leite"]
basically, you create a new array, then you map the results you have and push the value you want into this new array and you send it to your api
You can convert the array to an array of names as this
const arr = [
{
"id": 8,
"isSelected": true,
"name": "leite condensado",
},
{
"id": 9,
"isSelected": true,
"name": "creme de leite",
},
]
const names = arr.map(obj => {
return obj.name
})
console.log (names)
I have the same problem as up,I want to convert the Array of post objects received from jsonplaceholder by Axios to an Array of "post ids" and send it by array data to the reducer.js. After follow up solution, I get the correct answer as below.
axios.get('http://jsonplaceholder.typicode.com/posts?_start=10&_limit=5')
.then((res)=>{
const data=res.data
const ids = data.map(obj=>{
return obj.id
console.log('axios success:'+ids)
})
Console output as below:
axios success:11,12,13,14,15
I have an output of REST API in following JSON format:
I need to convert the format to flat format so it can be passed as input to another API call.
{
"result": {
"data": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
},
// ... 1000's of rows like this
]
}
}
I need to convert it in below format using a java-script
Desired format:
{"result":{ "data":[{"id":"b3","dateTime":"2019-09- 10T11:32:05.220Z","DiagnosticAccelerationSideToSideId":0,"DiagnosticAccelerationForwardBrakingId ":2.824315071105957},...
The rows needs to be merged with primary key as combination of ID and dateTime attributes. Please note the diagnostic id value becomes key for the required format and data value is the value of the key.
Is there any way to convert this JSON to above flat format.
Need to convert JSON having many rows for single data entry to single row format. Need one java-script function that can accept a string of rows format and convert or merge it and return the string in desired format
function String mergeRows(String flatDataJSONString) {
...
}
If the items are ordered (meaning i and i+1 are merged) than iterate with jumps of i += 2;
If its not ordered or the amount of items to be merged can be > 2 you use an object with unique key composed of the id and date, and override its data whenever a record match this key:
function merger (jsonStr) {
// convert str to obj
const jsonObj = JSON.parse(jsonStr);
const dataObj = {};
for (let i = 0; i < jsonObj.result.length; i++) {
const item = jsonObj.result[i];
// use unique key to merge by
const itemUniqueKey = item.device.id + item.dateTime;
// take last value or create empty object if not exists
const existingItem = dataObj[itemUniqueKey] || {};
// add some logic to merge item with existingItem as you need
...
// set the result back to dataObj to be used on next merges
dataObj[itemUniqueKey] = [merge result of item and existing item];
}
// take dataObj values, you don't need the keys any more
const dataArr = Object.values(dataObj);
const finalResult = {
result: {
data: dataArr
}
}
// convert back to json
return JSON.stringify(finalResult);
}
As stated in the comment you want first to have a clean json definition in order to stringify it. Please get to the following definition of your JSON first:
const json = {
"result": [
{
"data": 2.824315071105957,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationForwardBrakingId" },
"controller": "ControllerNoneId",
"version": "00000000000363b0",
"id": "a5UyPzhknSC-N2wtLBph3BA"
},
{
"data": 0,
"dateTime": "2019-09-10T11:32:05.220Z",
"device": { "id": "b3" },
"diagnostic": { "id": "DiagnosticAccelerationSideToSideId" },
"controller": "ControllerNoneId",
"version": "00000000000363b1",
"id": "a5UyPzhknSC-N2wtLBph3BQ"
}]
};
and then you will be able to perform like hereafter :
JSON.stringify(json)
Hope this helps !
I am using AngularJS. I have a json object as below;
info = [
{
"name": "Tom",
"id": "111"
},
{
"name": "Sam",
"id": "222"
},
{
"name": "James",
"id": "333"
}
]
I want to have a function such that when a matching name is found, some action is taken (in this -case, return the corresponding id.) In other words, if the input matching name is 'Tom', I want to return the id '111' based on the json object above.
I wrote some code to find a matching name.
$scope.getIdFromName = function()
{
angular.forEach(info, function(value, key)
{
//$scope.searchByName contains the name to be matched
if (key === 'name' && value === $scope.searchByName)
{
//$scope.searchById is the id to be returned
$scope.searchById = key;
alert("found");
}
});
};
Where did the code go wrong? Or is it so wrong that it is better to be completely rewritten? Any suggestions (does not need to be angularjs) will be most welcome. Thank you very much.
Since info is an array of objects, the key is going to be the index of each item, and value will be the whole object at that index. Your forEach should look like this:
angular.forEach(info, function(value, key)
{
//$scope.searchByName contains the name to be matched
if (value.name === $scope.searchByName)
{
//$scope.searchById is the id to be returned
$scope.searchById = value.id;
alert("found");
}
});