Search in array of objects that sits in object in array - javascript

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.');
}

Related

Is there any other way to check multiple values are present in array of object?

I have the below array of objects and I want to check if two different users are present in this array .if present i have to run some logic
let result = [{"name": "ABC"},{"name": "CDE"},{"name": "FGH"},{"name": "XYZ"}];
var newArr = [];
var hasMatch = result.filter(function(val) {
if (val.name == "FGH"){
newArr.push(val)
} else if (val.name == "ABC") {
newArr.push(val)
}
});
console.log(newArr)
if (newArr.length == 2) {
//do logic
}
It's working as expected but I'm looking for a different approach for this. could someone advise?
Not optimized for speed, but does the job
let arr = [
{
"name": "ABC"
},
{
"name": "CDE"
},
{
"name": "FGH"
},
{
"name": "XYZ"
}
];
let users = ["ABC", "XYZ"]
let hasAllUsers = users.every(user => arr.some(item => item.name == user))
console.log(hasAllUsers)
// if(hasAllUser) {...}
It's a pretty roundabout way to zero in on the logic you're trying to express. Note how the result in hasMatch is never even used. That's really all you're looking for, does the array "have the values".
There's no need to push values to another array and check if that array has values. Just check of the original array has them.
Which could be as simple as:
let result = [{"name": "ABC"},{"name": "CDE"},{"name": "FGH"},{"name": "XYZ"}];
if (result.filter(r => r.name === "FGH" || r.name === "ABC").length === 2) {
// do logic
}
Or if you want to refactor the condition into a variable:
let result = [{"name": "ABC"},{"name": "CDE"},{"name": "FGH"},{"name": "XYZ"}];
let hasMatch = result.filter(r => r.name === "FGH" || r.name === "ABC").length === 2;
if (hasMatch) {
// do logic
}
Or a bit more verbose for clarity:
let result = [{"name": "ABC"},{"name": "CDE"},{"name": "FGH"},{"name": "XYZ"}];
let filteredResult = result.filter(r => r.name === "FGH" || r.name === "ABC");
let hasMatch = filteredResult.length === 2;
if (hasMatch) {
// do logic
}
You can simply create another array with the valid users and filter your array to match each items that are this array.
This can be done using the Array#includes method
const users = [{"name": "ABC"},{"name": "CDE"},{"name": "FGH"},{"name": "XYZ"}];
const validUsers = ["ABC", "FGH", "AnotherUser"];
const matchUsers = users.filter(user => validUsers.includes(user.name))
console.log(matchUsers)
You could count the wanted names.
const
data = [{ name: "ABC" }, { name: "CDE" }, { name: "FGH" }, { name: "XYZ" }],
names = ['ABC', 'FGH'],
result = data.reduce((t, { name }) => t + names.includes(name), 0);
console.log(result);
Try using a named function and pass in the array, key, and one or more values with the rest operator ...values. Use .flatMap() to filter with
[...values].includes(obj[key])
// ["ABC", "XYZ"].includes(obj.name)
and any non-match returns an empty array []. The final return is an array with a sub-array and the length of said sub-array.
const result = [["ABC", "XYZ"], 2]
// result[0][0] = "ABC"
// result[0][1] = "XYZ"
// result[1] = 2
const arr = [{"name": "ABC"},{"name": "CDE"},{"name": "FGH"},{"name": "XYZ"}];
function hasMatch(array, key, ...values) {
const result = array.flatMap((obj, idx) =>
[...values].includes(obj[key]) ? obj : []);
return [result, result.length];
}
console.log(hasMatch(arr, "name", "ABC", "XYZ"));
console.log(hasMatch(arr, "name", "FGH", "IJK", "LMN", "ABC", "XYZ"));

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

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

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.

How to check value exist on column Type on array of object report Control?

I need to check column Type value but it not catch or give me message column type exist ON console log
ReportControl: any[] = []
this.ReportControl
value of ReportControl is
[
{
"reportId": 2028,
"fieldName": "offilneURL",
"reportStatus": "HiddenColumn",
"columnType": 1
},
{
"reportId": 2028,
"fieldName": "onlineUrl",
"reportStatus": null,
"columnType": 2
}]
I need to check columnType=2 so I write
if (this.ReportControl["columnType"] == 2) {
console.log("column type exist");
}
it does not catch message console log column type exists
Why what is wrong and How to solve that?
As I'm seeing from the provided code, ReportControl is an array of objects not a simple array and not a simple object. So you need to iterate through that array and then check if columnType exists and check its value.
For example you can do the following:
1/ Start by iterating the ReportControl array:
this.ReportControl.map((reportElement) => {
});
2/ Do you check inside the map method:
if("columnType" in reportElement && reportElement["columnType"] == 2) {
console.log("column type exist in report " + reportElement["reportId"]);
}
So the full code will be:
this.ReportControl.map((reportElement) => {
if("columnType" in reportElement && reportElement["columnType"] == 2) {
console.log("column type exist in report " + reportElement["reportId"])
}
});
There are multiple methods which you can use to achieve this behavior but I think this is the simplest.
Since its an array, you have to loop over your elements
var reportControl = [{
"reportId": 2028,
"fieldName": "offilneURL",
"reportStatus": "HiddenColumn",
"columnType": 1
},
{
"reportId": 2028,
"fieldName": "onlineUrl",
"reportStatus": null,
"columnType": 2
}
]
let found = false;
for (let i = 0; i < reportControl.length; i++) {
if (reportControl[i]['columnType'] === 2 && reportControl[i].fieldName === 'onlineUrl') {
found = true;
break;
}
}
if (found) {
console.log("column type exist");
}
Note that this is plain javascript. Since you are using angular, you have to replace reportControl with this.ReportControl
As you have an array of object you need to check each object for value as below.
var rc = [
{
"reportId": 2028,
"fieldName": "offilneURL",
"reportStatus": "HiddenColumn",
"columnType": 1
},
{
"reportId": 2028,
"fieldName": "onlineUrl",
"reportStatus": null,
"columnType": 2
}
];
var isValueexistt = false;
for (let i = 0; i < rc.length; i++) {
var obj = rc[i];
isValueexistt = obj["columnType"] == 2 && obj["fieldName"] == 'onlineUrl';
if (isValueexistt) {
break;
}
}
console.log(isValueexistt);

React iterate recursively through nested objects

i'm trying to iterate recursively over nested objects to get the key and the value.
My data structure is:
{
"id": 8743077530231325861,
"name": "Name of XYZ",
"key X": 0,
"key Y": {
"details": {
"value": {
"up": 5,
"down": 3
},
"path": "xyz"
},
"key Z": {
"value": 1,
"path": "abc"
}
},
"createdTimestamp": 1554446703000
}
and my function is:
recursion = (item, keyString) => {
if(isObject(item)){
Object.keys(item).map((key) => {
return this.recursion(item[key], keyString+`.${key}`)
})
}else{
return {item, keyString}
}
}
and i call it by:
Object.keys(data).map(key =>{
console.log(this.recursion(data[key], key))
})
My problem is that keys which are objects are always undefined.
I know thats because they need to iterate an other time and the output is faster then the function. When i print out the values at the end of the recursion function instead of returning them, they are not undefined.
At the end i want for every key all the deepest values and "paths". For Example
8743077530231325861,"id"
Name of XYZ,"name"
0, "keyX"
5, "keyY.details.value.up"
...
I already tried to use await / async but i cant manage to get all values
would be nice if someone have a hint for me
You need to return the result of mapping.
const
isObject = v => v && typeof v === 'object',
recursion = (item, path = '') => isObject(item)
? Object
.keys(item)
.flatMap(k => recursion(item[k], path + (path && '.') + k))
: { item, path };
var data = { id: 8743077530231326000, name: "Name of XYZ", "key X": 0, "key Y": { details: { value: { up: 5, down: 3 }, path: "xyz" }, "key Z": { value: 1, path: "abc" } }, createdTimestamp: 1554446703000 },
result = recursion(data);
console.log(result);

Categories