Angular: How to get the values of the array of objects - javascript

I am trying to get the values of the array of objects using filer in angular but unable to find the solution. Most probably missing something.
channels: {
"channelId": 18,
"platforms": [
{
"name": "android",
"isRecordable": "Y",
},
{
"name": "ios",,
"isRecordable": "Y",
},
{
"name": "pctv",
"isRecordable": "Y",
},
{
"name": "pctv",
"isRecordable": "Y",
},
{
"name": "stb",
"multicastIp": "224.0.251.1",
"multicastPort": 8002,
"isRecordable": "Y"
}
]
}
I want to get the value of a multicast ip where platformName = stb and multicastIp should not be null.
Can someone please explain how to do it.

Use the filter() and find() JavaScript array methods.
//Your array
const platforms = channelConfig.platforms;
const arr = plaforms.filter(platform => { return platform.multicastIp != undefined && platform.name == 'stb' });

let multiCastIps = []
channelconfig.platforms.forEach((platform) => {
if(platform.name == 'stb' && platform.multicastIp != null){
multiCastIps.push(platform)
// pushing only the platforms where name = stb and mltucastip != null
}
});
Short way:
let multiCastIps= channelconfig.platforms.filter(platform => { return platform.name == 'stb' && platform.multicastIp != null});

I would do it like this:
const STB_PLATFORM = "stb";
const stbPlatform = channels.platforms.find(p => p.name == STB_PLATFORM && !!p.multicastIp);
let multicastIP = stbPlatform ? stbPlatform.multicastIp : "Not Available";
The STB_PLATFORM could be a parameter to a search function or a component constant.

Related

Loop through array of differently structured JSON objects/arrays

I feel like this is mostly an issue with how I'm looping through the JSON, so am posting that first. This is a series of JSON responses from Promise.allSettled() posted below.
The problem I am having is with the second "status" object between content and anoObject1 as I'm looping through the JSON responses. I've shown some console.logs() below that are successful
Here is the series of JSON responses:
[
{
"status": "fulfilled",
"value": {
"content": {
"object1": {
"kv": "Y",
"kv1": "1000",
"kv2": {
"okv": "A",
"okv1": "1"
},
"kw": "A"
}
},
"retrievalDate": "2022-05-04T23:01:57.710+0000"
}
},
{
"status": "fulfilled",
"value": {
"content": [
{
"anoObject1": {
"ano": "A",
"ano1": {
"ona": "B",
"ona1": 11
},
"measureValue": "1.92",
"measureValue2": "N"
}
},
{
"anoObject2": {
"ano": "B",
"ano1": {
"ona": "Y",
"ona1": 11
},
"measureValue": "1.92",
"measureValue2": "N"
}
}
],
"retrievalDate": "2022-05-04T23:01:57.707+0000"
}
}
]
Here are the async fetch calls:
export async function allCallouts(key, value){
const BASE_URL = 'https://baseurl.com/service/'
const API_KEY = 'apikey'
const endpoint1 = 'https://url1.com/a/';
const endpoint2 = 'https://url1.com/b/';
try{
const results = await Promise.allSettled(
[
fetch(endpoint1).then((response) => response.json()),
fetch(endpoint2).then((response) => response.json()),
]
)
return results
} catch (error){
console.log(error)
}
}
Here is the function I am calling the first function from
async handleFetchCallouts() {
returnedResults;
await allCallouts(key, value)
.then(results => {
this.returnedResults = results
}).catch(err => {
console.log('this is err: ' + err);
})
let arrayLength = this.returnedResults.length
for (var i = 0; i < arrayLength; i++) {
//I am able to console.log(this.returnedResults[i].value.content)
//it returns the response and number I am expecting
//but the structure of the JSON response (above) is tripping me up
if (this.returnedResults[i].value.content['object1'] != null) {
//I can console.log() this successfully
console.log(this.returnedResults[i].value.content['object1'].kv)
}
if (this.returnedResults[i].value.content['anoObject1'] != null) {
//having trouble getting to this object and looping through each
}
}
}
Thank you for any help! If you see other design flaws with my code or an easier way to do things, please suggest.
Create a recursive function and dont use any hardcoded key. Iterate through the content and check if value is an array using Array.isArray. If so then handle it in a different function and so for if value is of type object
const arrayLength = [{
"status": "fulfilled",
"value": {
"content": {
"object1": {
"kv": "Y",
"kv1": "1000",
"kv2": {
"okv": "A",
"okv1": "1"
},
"kw": "A"
}
},
"retrievalDate": "2022-05-04T23:01:57.710+0000"
}
},
{
"status": "fulfilled",
"value": {
"content": [{
"anoObject1": {
"ano": "A",
"ano1": {
"ona": "B",
"ona1": 11
},
"measureValue": "1.92",
"measureValue2": "N"
}
},
{
"anoObject1": {
"ano": "B",
"ano1": {
"ona": "Y",
"ona1": 11
},
"measureValue": "1.92",
"measureValue2": "N"
}
}
],
"retrievalDate": "2022-05-04T23:01:57.707+0000"
}
}
]
for (let i = 0; i < arrayLength.length; i++) {
const content = arrayLength[i].value.content;
// checking if value is of type array or object
if (Array.isArray(content)) {
handleContentArray(content)
} else if (content && typeof(content) === 'object') {
handleContentObject(content)
}
}
function handleContentArray(contentArray) {
// iterate the array
contentArray.forEach(item => {
// if the content of the array is an object then call the function which handles the object
if (item && typeof item === 'object') {
handleContentObject(item)
}
})
}
function handleContentObject(contentObject) {
// iterate through the key
for (let keys in contentObject) {
// if the value of the key is an object then recursively call the same function
if (contentObject && typeof(contentObject[keys]) === 'object') {
return handleContentObject(contentObject[keys])
} else {
// log the key value pair
console.log(`KEY:- ${keys}, VALUE: - ${contentObject[keys]}`)
}
}
}
You can use Array.isArray() to ascertain if an object is an Array and customize how you handle the object accordingly.
// Same structure as in the question, but removed extraneous
// fields and compacted for the sake of brevity.
const input = `[
{"value":{"content":{"object1":{"kv":"Y"}}}},
{"value":{"content":[
{"anoObject1":{"ano":"A"}},
{"anoObject1":{"ano":"B"}}
]}}]`;
const result = JSON.parse(input);
for (const r of result) {
const content = r.value.content;
if (Array.isArray(content)) {
for (const c of content) {
console.log(`anoObject1.ano = ${c.anoObject1.ano}`);
}
} else {
console.log(`object1.kv = ${content.object1.kv}`);
}
}
For your second if statement in the for loop, you would have to iterate through all items under value.content. Replace the second if statement with this for a plug and play:
if (Array.isArray(this.returnedResults[i].value.content)) for (let i of this.returnedResults[i].value.content) {
}
Inside the new loop, i will be equivalent to
{
"anoObject1": {
"ano": "A",
"ano1": {
"ona": "B",
"ona1": 11
},
"measureValue": "1.92",
"measureValue2": "N"
}
}
The reason for this is that the second if statement was attempting to find a property/key of an array instead of each object in the array of objects.
I would also recommend reading up on the following to make your coding easier/better:
let
for...in/for...of
truthy/falsy

How to add and remove values from local storage on checkbox click in Angular8

i have dynamic generated list of checkbox, i want to create array with objects.
I wanted to push data in array of objects if value is true and setItem to localStorage,
and if value is false then it will remove objects from local storage
Can anyone help me to optmize my code with expected output.
Expected output
[
{
"key": "Test",
"value": true
},
{
"key": "Test1",
"value": true
},
{
"key": "removeItem",
"value": false
}
]
Code
setColumn($event, item) {
var obj = {}, valueAliasPair = [];
if (item.tabelHeader.data != '' && $event.checked === true) {
obj['key'] = item.tabelHeader.data;
obj['value'] = $event.checked;
valueAliasPair.push(obj);
localStorage.setItem('AvailableAmt', JSON.stringify(valueAliasPair));
}
if (item.tabelHeader.data != '' && $event.checked === false) {
localStorage.removeItem('AvailableAmt', obj['key']);
}
console.log(valueAliasPair, "valueAliasPair");
}
Updated:
setColumn($event, item) {
let valueAliasPair = JSON.parse(localStorage.getItem("AvailableAmt") || "[]");
if (item.tabelHeader.data != "") {
if ($event.checked) {
valueAliasPair.push({
key: item.tabelHeader.data,
value: true,
});
localStorage.setItem("AvailableAmt", JSON.stringify(valueAliasPair));
} else {
const ind = valueAliasPair.findIndex((x) => x.key === item.tabelHeader.data);
valueAliasPair.splice(ind, 1);
localStorage.setItem("AvailableAmt", JSON.stringify(valueAliasPair));
}
}
console.log(valueAliasPair, "valueAliasPair");
}

Get path of an element inside a JSON object

I have an object like the following :
[
{
"uid": "aaa-aaa",
"name": "foo",
"children": []
},
{
"uid": "aaa-bbb",
"name": "bar",
"children": [
{
"uid": "aaa-bbc",
"name": "baz",
"children": []
},
{
"uid": "aaa-ccc",
"name": "fooz",
"children": [
{
"uid": "aaa-bcb",
"name": "Yeah !",
"children": []
}
]
}
]
}
]
I am trying to write a function that would take that object an uid as parameters and would return a path to the element with the uid in that object (or null if it's not found).
Something like this :
> getElementPath(bigObject, 'aaa-bcb')
[1, "children", 1, "children", 0]
or
> getElementPath(bigObject, 'aaa-bcb')
[1, 1, 0]
I know the function has to be recursive since there should be no limit in nesting levels. I have tried this but it always returns null :
function getElementPath (haystack, uid, currentPath = []) {
if (haystack.uid === uid) {
return currentPath
}
if (Array.isArray(haystack.children)) {
for (let i = 0; i < haystack.children.length; i++) {
let newPath = [...currentPath, i]
let path = getElementPath(haystack.children[i], uid, newPath)
if (path !== null) {
return path
}
}
}
return null
}
I'd use flat
Flatten the object and then loop over the Object keys until you find the one that has the appropriate value. Once you find it, the key is the path.
https://www.npmjs.com/package/flat
My (naive and quick) implementation would look like this. But what I don't love about it is that it knows to look at the "children" property, it's fine if you're data structure is well defined and doesn't change very often, the flat idea will work no matter if you change your data structure or not.
getPathForUid = (uid,obj,thisPath = []) => {
if(Array.isArray(obj)) {
return obj.reduce((acc,item,idx) => getPathForUid(uid,item,thisPath.concat(idx)),[]);
}
return obj.uid === uid ? thisPath : getPathForUid(uid,obj.children,thisPath.concat('children'));
}
Try this:
function getObject(listaJson, uid) {
var object = null,
param,
type = null;
if (listaJson.uid === uid) {
return listaJson;
}
for (param in listaJson) {
type = typeof(listaJson[param]);
if (type.toString().toLowerCase() === 'object') {
object = getObject(listaJson[param], uid);
}
if (object) {
return object;
}
}
return object;
}
console.log(getObject(json, 'aaa-aaa'));
console.log(getObject(json, 'aaa-bbb'));
console.log(getObject(json, 'aaa-bbc'));
console.log(getObject(json, 'aaa-ccc'));
console.log(getObject(json, 'aaa-bcb'));
console.log(getObject(json, 'aaa-xxx')); // null
console.log(getObject(json, 'yyy-jjj')); // null

Search in array of objects that sits in object in array

I need to check if bidder "one" already has "placementId": "4" in arr.
I've tried to combine for loop with filter with no luck. Is there any elegant way to solve this?
var check = { "one": "4" },
arr = [{
"code": "qwe",
"bids": [{
"bidder": "one",
"params": {
"placementId": "1"
}
},
{
"bidder": "two",
"params": {
"placementId": "2"
}
}
]
}, {
"code": "asd",
"bids": [{
"bidder": "one",
"params": {
"placementId": "3"
}
}]
}];
I think find() is the way to go here. You want to find an element in your array where one of the bids has a bid.bidder of "one" and bid.params.placementId of 4. Or undefined if it doesn't exist.
This can be expressed in javascript with something like:
let found = arr.find(code =>
code.bids.some(bid => bid.bidder === "one" && bid.params.placementId === "4"))
Since you only want to know whether it exists or not you basically only care if it returns something or undefined. Here's a positive and negative example:
var check = { "one": "1" },arr = [{"code": "qwe","bids": [{"bidder": "one","params": {"placementId": "1"}},{"bidder": "two","params": {"placementId": "2"}}]}, {"code": "asd","bids": [{"bidder": "one","params": {"placementId": "3"}}]}];
// user one placement id 4 does not exist
let found = arr.find(code => code.bids.some(bid => bid.bidder === "one" && bid.params.placementId === "4"))
console.log(found !== undefined)
// user two placement id 2 does exist
found = arr.find(code => code.bids.some(bid => bid.bidder === "two" && bid.params.placementId === "2"))
console.log(found !== undefined)
Use this code:
arr.forEach(element => {
element.bids.forEach(item=>{
if(item.bidder == Object.keys(check)[0]){
if(item.params.placementId == 1){
console.log("bidder 1 and placementId 1 found");
}
}
});
});
var bidders = {};
arr.forEach((field)=>{
let bidArray = field.bids.map((bids)=>{
if(bidders[bids.bidder] === undefined){
bidders[bids.bidder] = []
}
return {bidder:bids.bidder,placementId:bids.params.placementId};
})
for(let placement of bidArray){
bidders[placement.bidder].push(placement.placementId);
}
})
console.log(bidders);
To list out all the bidders and their respective placements
then you can do
if(bidders.one.indexOf(4) !== -1){
console.log('Placement 4 is taken by bidder 1.');
}
else{
console.log('Placement 4 is not taken by bidder 1.');
}

add key and value in json file using javascript

the data.json look like
[
{
"uid": 11111,
"status": "ADMIN"
},
{
"uid": 22222
}
]
i use lodash for find the key uid = 22222
_.find(data, (item)=>item.uid === 22222)
the result is {uid: 22222}
how can i add some status: "value" in result that i find by lodash
i expect like this
[
{
"uid": 11111,
"status": "ADMIN"
},
{
"uid": 22222,
"status": "USER"
}
]
You can use _.find() to get the object, and _.set() to update it:
var data = [{"uid":11111,"status":"ADMIN"},{"uid":22222}];
_.set(_.find(data, function(obj) { return obj.uid === 22222; }), 'value', 'USER');
_.set(_.find(data, function(obj) { return obj.uid === 23322; }), 'value', 'USER'); // no object was found and nothing changed
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
This gives you the object, so you can just work with it directly:
_.find(data, item => item.uid === 22222).status = "USER";
Otherwise you can get the index and update the entire object.
const idx = _.findIndex(data, item => item.uid === 22222);
data[idx] = Object.assign(data[idx], {status: "USER"});
Depending on the environment you're working in, you don't need to use lodash and you can just use data.find.
You do not need lodash, use Array.prototype.find:
var arr = [
{
"uid": 11111,
"status": "ADMIN"
},
{
"uid": 22222
}
]
// get correct item in array
var item = arr.find(i => i.uid === 22222)
// object is mutable, array have a pointer to the object
item.status = 'USER'
console.log(arr)
Here is a jsbin to play around.
If you are in an old environment (Internet Explorer mostly), use Array.prototype.filter:
// will be undefined if not found, so check for that
var item = arr.filter(i => i.uid === 22222)[0]

Categories