I want to remove object from array if they dont have a value
i have the API A, that returns to me this JSON:
{
"code": 0,
"data": [
{
"name": {
"value": "Ana"
},
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
]
}
and with the API B, i can return the id for this user passing her the name
i have this code:
getData() {
this.myService.getDataAPI_A()
.subscribe((res) => {
this.myList = res['data'];
if (this.myList) {
for (const key of this.myList) {
this.getId(key.name.value);
}
}
});
}
getId(name) {
this.myService.getDataAPI_B(name) // api B returns id with the name
.subscribe((res) => {
this.myList.map((tempList) => {
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
return tempList;
}
return tempList;
});
});
}
then i got this json:
{
"code": 0,
"custodyBovespa": [
{
"name": {
"value": "Ana"
},
"userId": "43",
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
]
}
Michael does not existe in my data base, so the api returns to me null,
and for some reason dont create the key in my json (why?).
after this i want to remove the object that dont have userId
how i can do this?
If you'd like your resultant array to contain only objects that contain the property userId, you can simply use plain JavaScript .filter.
In my below example, I am removing any element that does not have a "userId" prop.
var data = [
{
"name": {
"value": "Ana"
},
"userId": "43",
"fruit": {
"value": "Grape"
},
"from": {
"value": "BR"
}
},
{
"name": {
"value": "Michael"
},
"fruit": {
"value": "Apple"
},
"from": {
"value": "US"
}
}
];
var dataFiltered = data.filter(val => val["userId"]);
console.log(dataFiltered);
As you said:
Michael does not existe in my data base
and the condition you set is
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
return tempList;
}
return tempList;
As the your database doesn't have the the value 'Michael', The above condition is false. So, it gets out of the if clause and just return what it is without userId.
Now if you want to set the 'Michael' userId to null.
if (res.name === tempList.name.value) {
tempList.userId = res.id; // creating a key and setting value
} else {
tempList.userId = null;
}
return tempList;
Then filter out the data's using like #Rich answered.
console.log(data.filter(val => val['userId'] !== null);
Related
Fairly new to this but can someone help me?
I have the following JSON:
{
"city": [
{
"city_description": {
"text": {
"st": "capital"
}
},
"city_land": {
"st": {
"st": "Other"
}
},
"city_size": {
"id": [
{
"id": "small"
},
{
"id": "big"
},
{
"id": "moderate"
}
]
},
"city_type": {
"id": [
{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
},
"conception_date": {
"st": {
"st": "13051977"
}
},
"mark_row": {
"id": {
"id": "1"
}
}
},
{
"city_description": {
"text": {
"st": "cottage"
}
},
"city_land": {
"st": {
"st": "Other"
}
},
"city_size": {
"id": [
{
"id": "small"
},
{
"id": "big"
},
{
"id": "moderate"
}
]
},
"city_type": {
"id": [
{
"id": "1"
},
{
"id": "2"
},
{
"id": "3"
}
]
},
"conception_date": {
"st": {
"st": "15071999"
}
},
"mark_row": {
"id": {
"id": "2"
}
}
}
],
"country": {
"country_code": {
"coordinates": {
"id": "00111022"
},
"name_of_country": {
"st": "Belarus"
},
"desc": {
"st": "Non-eu"
}
},
"country_identifier": {
"id": {
"id": "99"
}
},
"country_description": {
"st": {
"st": "TBD"
}
},
"country_type": {
"is": [
{
"is": "01"
},
{
"is": "X90"
}
]
},
"country_id": {
"si": {
"si": "3"
}
}
}
}
This is stored in snowflake as a string.
I am able to select the data (eg. first column) for the first array.
I am able to select the data (eg. first column) for the first array:
SELECT
f.VALUE:city_description:text:st AS city_description
FROM tableinsnowflake t,
LATERAL flatten(input => t.PARSED_DATA, path => 'city') f
I want to do the same for COUNTRY but seem somehow stuck. Any thoughts? Thanks!
The country could be accessed directly from parsed_data column without using FLATTEN:
SELECT
f.VALUE:city_description:text:st::TEXT AS city_description,
t.parsed_data:country:country_code:name_of_country:st::TEXT AS name_of_country
FROM tab t,
LATERAL FLATTEN(input => t.PARSED_DATA, path => 'city') f
In the code below, I am trying to make an array and remove duplicates from array with reactjs:
The array called names is set in state:
this.state = {
names = []
}
How can I remove the duplicated names and place them into the array
const data = [
{
"obj": {
"no": "1",
"info": [
{
"name": "maya"
},
{
"name": "mina"
}
]
}
},
{
"obj": {
"no": "2",
"info": [
{
"name": "maya"
}
]
}
},
{
"obj": {
"no": "3",
"info": [
{
"name": "mina"
},
{
"name": "Mike"
}
]
}
}
]
data.map((elem) => {
for(let i = 0 ; i < elem.info.length;i++){
let name_info = elem.info[i].name
this.setState({
names: [...this.state.names, name_info]
})
}
})
expected output :["maya","mina",Mike]
If you're fan of one line
[...(new Set(data.map(d => d['obj']['info']).flat().map(info => info['name'])))]
Step by step explanation:
First map takes the input returns only info part of each entry:
data.map(d => d['obj']['info']) yields array of array containing info.
[[{ name: "maya" }, { name: "mina" }], [{ name: "maya" }], [{ name: "mina" }, { name: "Mike" }]]
flat() takes the input from previous map which is the array of array and yields array of elements, so it becomes
[{ name: "maya" }, { name: "mina" }, { name: "maya" }, { name: "mina" }, { name: "Mike" }]
map() takes the input from previous flat which is array of object (which contains name) and returns array of name value.
So you got [ "maya", "mina", "maya", "mina", "Mike" ]
The final array is given to Set, by definition set cannot contain same element more than one. Set of previous array is [ "maya", "mina", "Mike" ].
As final step, set is converted to the array by using spread operator.
const data = [
{
"obj": {
"no": "1",
"info": [
{
"name": "maya"
},
{
"name": "mina"
}
]
}
},
{
"obj": {
"no": "2",
"info": [
{
"name": "maya"
}
]
}
},
{
"obj": {
"no": "3",
"info": [
{
"name": "mina"
},
{
"name": "Mike"
}
]
}
}
];
let names = [];
data.forEach(item => {
Object.values(item)[0].info.forEach(person => {
if(names.indexOf(person.name) === -1)
{
names.push(person.name)
}
})
})
console.log(names);
I think this can help you
First, this is a helper function to get just the unique value of an array
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
And, this is how can get the result you want
const newNames = data.map((elem) => elem.obj.info.map(info => info.name)).flat().filter(onlyUnique)
You can then use it like this
this.setState({
names: [...this.state.names, ...newNames]
})
const data = [{
"obj": {
"no": "1",
"info": [{
"name": "maya"
}, {
"name": "mina"
}]
}
}, {
"obj": {
"no": "2",
"info": [{
"name": "maya"
}]
}
}, {
"obj": {
"no": "3",
"info": [{
"name": "mina"
}, {
"name": "Mike"
}]
}
}]
const names = data.flatMap(obj => obj.obj.info.map(info => info.name));
const unique = names.filter((name, i) => names.indexOf(name) === i);
console.log(unique);
I have this json respone from postman
I want to write a test to return failure if key "value" in the array is < 50.
It would loop through the array once the condition is not met it fails
I have tried this
pm.test('Matches value', () => {
_.each(pm.response.json(), (arrItem) => {
if (arrItem.persID === 'personID_2') {
throw new Error(`Array contains ${arrItem.persID}`)
}
})
});
My response
{
"groups": [
{
"title": "Maids",
"subTitle": null,
"description": null,
"featured": false,
"items": [
{
"id": "1",
"title": "AA",
"subTitle": "AA",
"thumbnail": "AA",
"priceStartingAt": {
"value": 50,
"baseCurrency": "USD",
"exchangeEnabled": true,
"exchangeRates": {
"aed": 3.672973
}
},
"categories": [
"Activity"
]
},
{
"id": "2",
"title": "BB",
"subTitle": "BB",
"thumbnail": "BB",
"priceStartingAt": {
"value": 20.01,
"baseCurrency": "USD",
"exchangeEnabled": true,
"exchangeRates": {
"aed": 3.672973
}
},
"categories": [
"Activity"
]
}
]
}
]
In this case the test should fail because the value in the second array is 20.01
I'm not sure where you copied that code from but it was never going to work as all the references relate to a different response body.
To keep the same convention and have the throw new Error in there you could do this:
pm.test('Value is not below 50', () => {
_.each(pm.response.json().groups[0].items, (arrItem) => {
if (arrItem.priceStartingAt.value < 50) {
throw new Error(`Array contains ${arrItem.priceStartingAt.value}`)
}
})
});
Or you could just check if the items are not below 50 like this.
pm.test('Value is not below 50', () => {
_.each(pm.response.json().groups[0].items, (arrItem) => {
pm.expect(arrItem.priceStartingAt.value).to.not.be.below(50)
})
});
I have an object array and i am filtering it against property name "username" like this.
array = [{
"id": 1,
"username": "admin",
"roles": [{
"name": "Administrator"
},
{
"name": "agent"
}
]
},
{
"id": 2,
"username": "admin2",
"roles": [{
"name": "Administrator2"
},
{
"name": "agent2"
}
]
},
{
"id": 3,
"username": "admin3",
"roles": [{
"name": "Administrator3"
},
{
"name": "agent3"
}
]
}
]
and the filter function is like this
transform(array: any, valueToSearch: string): any[] {
return array.filter(e =>
e.username.toLowerCase().indexOf(valueToSearch.toLowerCase())
!== -1);
}
everything works fine, but now i want to filter against the property name "name" in "roles" array in the object. for example i would like to return an object whose "roles" array contains "name" = agent3 , so it should return the whole object which is located at the last in my example. i tried like
return agents.filter(e => e.roles.filter(ee =>
ee.valueToSearch.toLowerCase()) !== -1));
but it didn't work.
this is dmeo
https://stackblitz.com/edit/angular-txchxs?embed=1&file=src/app/agentFilter.pipe.ts
As per the example given by you in the question, i was able to change your existing function like this and i hope this is your requirement..
ngOnInit() {
this.transform(this.array,'agent3');
}
transform(array: any, valueToSearch: string): any[] {
return this.array.filter(e => {
e.roles.filter(ee => {
if(ee.name.toLowerCase() === valueToSearch.toLowerCase() ) {
console.log(e);
this.finalResult = e;
}
})
})
}
Working Stackblitz: https://stackblitz.com/edit/angular-uzgni7
myarray = [{
"id": 1,
"username": "admin",
"roles": [{
"name": "Administrator"
},
{
"name": "agent"
}
]
},
{
"id": 2,
"username": "admin2",
"roles": [{
"name": "Administrator2"
},
{
"name": "agent2"
}
]
},
{
"id": 3,
"username": "admin3",
"roles": [{
"name": "Administrator3"
},
{
"name": "agent3"
}
]
}
];
function myFunction(){
var filtered= myarray.filter((obj)=>{
return obj.username.match(new RegExp(document.getElementById('search').value,'ig'));
});
console.log(filtered);
};
<input type="text" id="search" onkeyup="myFunction()"/>
I am currently using angular-schema-form-dynamic-select and my requirement is to select states based on a country selected. I'm storing data in the db like this country -> state -> city. Can anyone Help me on this?
This is my form:
[
{
"key": "country",
"type": "strapselect",
"placeholder":"country",
"options": {
"httpGet": {
"url": "/countries"
},
"map": { "valueProperty": "readonlyProperties.id", "nameProperty":"name" }
}
},
{
"key": "state",
"type": "strapselect",
"placeholder":"state",
"options": {
"httpGet": {
"url": "/states"
},
"map": { "valueProperty": "readonlyProperties.id", "nameProperty":"name" }
}
},
{
"key": "city",
"type": "strapselect",
"placeholder":"city",
"options": {
"httpGet": {
"url": "/cities"
},
"map": { "valueProperty": "readonlyProperties.id", "nameProperty":"name" }
}
}
]
I think a feature like that would be indeed quite handy. Maybe you write something like this in the json string:
{
"type": "object",
"properties": {
"country": {
"type": "string",
"enumCallback": "getTitlesValues()"
}
}
}
And in your controller you would have that callback defined:
...
$scope.getTitlesValues = function () {
return ['India','Australia', 'Germany', 'Sweden']
}
...
I think a feature like that would be indeed quite handy.
Maybe you write something like this in the json string:
{
"type": "object",
"properties": {
"country": {
"type": "string",
"enumCallback": "getTitlesValues()"
}
}
}
And in your controller you would have that callback defined:
...
$scope.getTitlesValues = function () {
return ['India','Australia', 'Germany', 'Sweden']
}
...