I'm trying to get two values from a JSON
Content of JSON:
[
{
"type":"session_start",
"properties":[
{
"property":"activity",
"type":"string"
}
]
}
]
to use in a component but been having trouble with getting the value of property
these are the codes I'm trying to use right now, but for some reason I get the error.
Property 'properties' does not exist on type 'Object'.
any ideas on how to make the outcome of props be "activity" ?
type = this.service.getData().pipe(map((response: any) => response.map((eventRead: { [x: string]: any; }) => eventRead['name'])));
props = this.service.getData().pipe(map(p => p?.properties?.property));
CodePudding user response:
properties
is inner array. So, you should call something like
props = this.service.getData().pipe(
map(p => {
const firstElement = p.properties.shift();
return firstElement.property;
})
);
props.subscribe(p => console.log(p)); // activity
CodePudding user response:
You just need to loop through the array of arrays, you can use flatMap
to flatten the array of arrays inorder to get the desired output!
const arr = [{
"type": "session_start",
"properties": [{
"property": "activity",
"type": "string"
}]
}]
const service = {
getData: () => rxjs.of(arr)
};
type = service.getData().pipe(rxjs.map((response) => response.map((eventRead) => eventRead['type'])));
console.log('type');
type.subscribe(console.log);
props = service.getData().pipe(rxjs.map(arrayData => {
const output = arrayData.flatMap(p => {
if (p.properties && p.properties.length) {
return p.properties.map(x => x.property);
}
return [];
})
// if you want an array output uncomment the below line!
// return output;
return output && output[0];
}));
console.log('props');
props.subscribe(console.log);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/7.5.6/rxjs.umd.min.js" integrity="sha512-yUlloKtrX4U41iKbaafsHrrwII0n1uAX9 3KzuaTjkfgLicBplGfr0vv7FtfwC5kgead1Dmr7sjunFFp0a s9Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Update:
It was due to autocomplete and options being mapped incorrectly with elementRef
CodePudding user response:
You can simply and directly get the value of "property" through,
const json = [
{
type: 'session_start',
properties: [
{
property: 'activity',
type: 'string',
},
],
},
];
var property = json[0].properties[0].property;
console.log(property);
Output:
activity
CodePudding user response:
You can use the optional chaining operator (?.) while accessing the properties array from the json to avoid the exception, you have to add checks for each level of the object.
if there is a single element in properties array then you can directly access the element by index like below:
let property = json[0]?.properties[0]?.property;
if there are multiple elements in properties array then you do something like below:
let prop = json[0]?.properties;
if(prop?.length > 1)
{
for(let i=0;i<prop.length;i )
{
//You can access the property data element here.
console.log(prop[i].property);
}
}