Unable to get blank properties and it's id from array of object - javascript

i want to get empty properties(only need to check role,group and subgroup) and it's id both in array of objects.
let tempdata = [
{
"id": 41,
"tool": "Artifactory",
"role": "",
"group": "Dish",
"subgroup": "Ehub test 009",
"subscriptionId": "artifactory-ehub-test-009"
},
{
"id": 4,
"tool": "Gitlab",
"role": "Owner",
"group": "IDP",
"subgroup": "IDP-Service-Templates",
"subscriptionId": "gitlab-51663585"
}
]
What i tried so far is this:
tempdata.filter(item=>item.group=='' || item.subgroup=='' || item.role=='').map(item=>item.id)
but this only gives my id [41] what i want is [{"id":41,"blank_properties":["role"]}]
Can somebody please help.

you can simply do it this way
tempdata.map((item)=>{
let d = [];
if(item.role === ''){
d.push('role')
}
if(item.group ===''){
d.push('group')
}
if(item.subgroup===''){
d.push('subgroup')
}
return {...item,'blank_prop':d}
})

tempdata.filter(item=>item.group=='' || item.subgroup=='' ||
item.role=='').map(item=>{
let temp=[];
if(item.group==='')temp.push('group')
if(item.role==='')temp.push('role')
if(item.subgroup==='')temp.push('subgroup')
if(item.subscriptionId==='')temp.push('subscriptionId')
if(item.tool==='')temp.push('tool')
return {id:item.id,blank_property:temp};})

I'm going to propose a more sophisticated solution, in case you're interested in additional ways to approach this problem:
let tempData =
[
{
"id": 41,
"tool": "Artifactory",
"role": "",
"group": "Dish",
"subgroup": "Ehub test 009",
"subscriptionId": "artifactory-ehub-test-009"
},
{
"id": 4,
"tool": "Gitlab",
"role": "Owner",
"group": "IDP",
"subgroup": "IDP-Service-Templates",
"subscriptionId": "gitlab-51663585"
},
];
// An array of all properties you want to check for blank strings
const propertiesToCheck = [ "group", "subgroup", "role" ];
result = tempData
.filter((item) =>
{
// Your original code was filtering the array of objects to
// JUST ones that have at least one of those properties set to ""
// So this filter does the same thing.
//
// If you DON'T actually want to outright remove ones that don't match this condition,
// then you can just remove this entire filter step.
// Iterate object keys and values
for (const [ key, value ] of Object.entries(item))
{
// If the key is not in the above array of propertiesToCheck,
// then skip it
if (propertiesToCheck.indexOf(key) == -1)
{
continue;
}
// If we encounter one of those properties and it's blank, return true
if (value == "")
{
return true;
}
}
// Return false if we get through all of the properties without encountering one that's blank
return false;
})
.map((item) =>
{
// Create an object to house the result in the manner you described
const result =
{
id: item.id,
blank_properties: [],
};
// Iterate the object keys and values again
for (const [ key, value ] of Object.entries(item))
{
// Same deal as before
if (propertiesToCheck.indexOf(key) == -1)
{
continue;
}
// Then, if the value is blank...
if (value == "")
{
// ...push its key to the blank_properties array
result.blank_properties.push(key);
}
}
// Return the result!
return result;
});
// Prints:
// [ { id: 41, blank_properties: [ 'role' ] } ]
console.log(result);

Related

How would I filter an array of objects by : If id numbers are consecutive

I have a JSON file that has an array of objects with data inside :
[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden#xerex.com",
"nameList": [
{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
}, ...
My job is to filter the arrays that have more than two names and if their id are consecutive.
I managed to sort users with more than two user.name but cant grasp the concept of filtering consecutive id numbers
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
Which returns me the objects with more than two user names.
filter takes a function that returns true if you want to retain the item or false if not. In this function, you could check the length of the nameList, and then iterate over its members and make sure their ids are consecutive:
retult = userData.filter(u => {
if (u.nameList.length < 2) {
return false;
}
for (let i = 1; i < u.nameList.length; ++i) {
if (u.nameList[i].id != u.nameList[i - 1].id + 1) {
return false;
}
}
return true;
});
a item should need tow conditions,one is nameList length is two ,the other is the itemId of nameList is consecutive;
so first as you do :
`
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
`
;
then
`
let lister4 = lister3.filter(names=>{
let idOfStr = names.nameList?.sort((a,b)=>a.id-b.id).map(item=>item.id).join("");
let resultStr = Array.from(idOfStr.length).fill(+idOfStr[0]).map((item,index)=>+item+index).join('');
return idOfStr === resultStr
})
`
hope this is useful for you

Javascript - Get occurence of json array with ESLINT 6

I can't set up an algo that counts my occurrences while respecting ESlint's 6 standards in javascript.
My input table is :
[
{
"id": 2,
"name": "Health",
"color": "0190fe"
},
{
"id": 3,
"name": "Agriculture",
"color": "0190fe"
},
{
"id": 1,
"name": "Urban planning",
"color": "0190fe"
},
{
"id": 1,
"name": "Urban planning",
"color": "0190fe"
}
]
And i want to get :
{"Urban planning": 2, "Health": 1, ...}
But that does not work with ESLINT / REACT compilation...
This is my code :
const jsonToIterate = *'MyPreviousInputJson'*
const names = []
jsonToIterate.map(item => (names.push(item.name)))
const count = []
names.forEach(item => {
if (count[item]){
count.push({text: item, value: 1})
} else {
count.forEach(function(top){top.text === item ? top.value =+ 1 : null})
}
})
Thank you so much
Well, you want an object in the end, not an array, so count should be {}. I also wouldn't use map if you're not actually returning anything from the call. You can use reduce for this:
let counts = topicsSort.reduce((p, c, i, a) => {
if (!p.hasOwnProperty(c.name)) p[c.name] = 0;
p[c.name]++;
return p;
}, {});
I'm half exppecting someone to close this as a duplicate because all you've asked for is a frequency counter. But here's an answer anyway:
const jsonToIterate = *'MyPreviousInputJson'*;
const names = {};
jsonToIterate.map(obj => {
if(obj.name in names){
names[obj.name]++
}
else{
names[obj.name] = 1;
}
})

How to add new value inside array of object by id (not new item)

I'm trying add a new value inside my array by id. I'm not trying add a new item in my array... For this I can use push(), but it add new item not a new value.
I'm trying do it:
My array:
const data =
[
{
"id": 1,
"year":2019,
"value": 2,
},
{
"id": 2,
"year": 2019,
"value": 89,
},
{
"id": 3,
"year": 2019,
"value": 99,
}
]
Inside an especific id I would to add a new value like this:
data.forEach(item => {
if(item.id === 2){
//data inside id 2 -> item: 55
}
})
So my new dataarray looks like this:
const data =
[
{
"id": 1,
"year":2019,
"value": 2,
},
{
"id": 2,
"year": 2019,
"value": 89,
"item": 55
},
{
"id": 3,
"year": 2019,
"value": 99,
}
]
In most of my searches, I found just how to add a new element. But this I know how to do (push()).
So how to add a new value inside specified id?
Just assign the property you want to add:
data.forEach(item => {
if(item.id === 2){
item.item = 55;
}
})
If the IDs are unique, you can use the .find() method:
var el = data.find(item => item.id === 2);
if (el) {
el.item = 55;
}
try
data.find(x=> x.id==2).item=55;
const data =
[
{
"id": 1,
"year":2019,
"value": 2,
},
{
"id": 2,
"year": 2019,
"value": 89,
},
{
"id": 3,
"year": 2019,
"value": 99,
}
]
data.find(x=>x.id==2).item=55;
console.log(data);
You can iterate and assign value based on your criteria
data.map(function(x){
if(x.id == 2){
x.value = 100;
}
})
You can implement method using Array.find to avoid unnecessary iterations:
const array = [
{
"id": 1,
"year":2019,
"value": 2,
},
{
"id": 2,
"year": 2019,
"value": 89,
},
{
"id": 3,
"year": 2019,
"value": 99,
}
];
const changeValue = (array, id, field, value) =>
array.find(el => el.id === id)[field] = value;
changeValue(array, 1, 'year', 9999);
console.log('result: ', array);
You have an array of objects and you want to add a field to one of the objects. So, first, you have to find the object you want to change. Array items can be accessed by index, but you don't know the index. There are several methods to find an item in an array.
var item = data.find(function(d, i){
return item.id === 2; //criteria
});
or in ES6 syntax:
var item = data.find(d=>d.id == 2);
after that, you can change item the way you want.
item.anotherField = 'another value';
As you said, push() adds an item to the array. It doesn't change existing items in the array.
Your code is more or less right there. To set the property of an item, you can do either object.propertyName = ... or object["propertyName"] = ....
With that, you'd simply need to update your example to look like this:
data.forEach(item => {
if(item.id === 2){
item.item = 55; //data inside id 2 -> item: 55
}
})
As a more efficient alternative, consider Array.find(). It won't continue to loop through the array after it finds the id, whereas your forEach will always loop through the array in its entirety.
const data = [ { "id": 1, "year":2019, "value": 2, }, { "id": 2, "year": 2019, "value": 89, }, { "id": 3, "year": 2019, "value": 99, } ];
( data.find(({id})=> id === 2) || {} ).item = 55;
console.log(data);
You'll notice I've followed the .find() with || {}. This is simply so that if an item with id === 2 isn't found, attempting to set the property won't throw an error.

How to append object-key value form one array to other array?

I have an existing array with multiple object. With an interval I would like to update the existing array with values from another array. See the (simplified) example below.
I've serverall gools:
Copy the value of fan_count form the new array, to the current array with the key "fan_count_new"
If a object is removed or added in the New array, it have to do the same to the Current array.
As far I can see now, I can use some es6 functions :) like:
object-assign, but how to set the new key "fan_count_new"?
How to loop through the array to compare and add or remove + copy the fan_count?
Current array:
[{
"fan_count": 1234,
"id": "1234567890",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
},
{
"fan_count": 4321,
"id": "09876543210",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
}, ...
]
New array:
[{
"fan_count": 1239,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
"id": "1234567890"
},
{
"fan_count": 4329,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
},
"id": "09876543210"
}, ...
]]
You can remove elements which doesn't exists in new array by using array.filter and you can loop through the new array to update the same object in the current array:
var currArr = [
{
"fan_count": 1234,
"id": "1234567890",
},
{
"fan_count": 4321,
"id": "09876543210",
},
{
"fan_count": 4321,
"id": "09876543215",
}
];
var newArr = [
{
"fan_count": 1234,
"id": "1234567890"
},
{
"fan_count": 5555,
"id": "09876543210"
}
];
currArr = currArr.filter(obj => newArr.some(el => el.id === obj.id));
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
found.fan_count_new = obj.fan_count;
}
});
console.log(currArr);
Later on I realised that is was better to turn it around, add the fan_count form the currArr to the new one. This because it is easier to handle new objects, and you dont't have to deal with deleted objects. So, anybody how is looking for something like this:
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
console.log('found: ', found.fan_count, obj.fan_count)
obj.fan_count_prev = found.fan_count;
obj.fan_count_diff = Math.round(obj.fan_count - found.fan_count);
}
if (typeof obj.fan_count_prev === "undefined") {
obj.fan_count_prev = obj.fan_count;
obj.fan_count_diff = 0
}
});

convert integer to array of object.

var items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
I have this array of objects named 'items'. I get itemselected = 3 from the database.
I need to convert this 3 into the following form.
0:Object
id:3
label:"Item3"
Similarly, if i have a value 2 coming from the database, i should convert it to
0:Object
id:2
label:"Item2"
Can anyone please let me hint of how to get it solved. i am not here to get the answer. These questions are quite tricky for me and i always fail to get the logic right. Any advice on how to master this conversions will be of great help. thanks.
Since you tagged underscore.js, this should be very easy:
var selectedObject = _.findWhere(items, {id: itemselected});
Using ECMA6, you can achieve the same using .find method on arrays:
let selectedObject = items.find(el => el.id === itemselected);
With ECMA5, you can use filter method of arrays. Be careful that filter returns undefined if no element has been found:
var selectedObject = items.filter(function(el) { return el.id === itemselected});
Use jquery $.map function as below
$.map(item, function( n, i ) { if(n["id"] == 3) return ( n );});
Based on the title of your question: «convert integer to array of object». You can use JavaScript Array#filter.
The filter() method creates a new array with all elements that
pass the test implemented by the provided function.
Something like this:
var items = [{
"id": 1,
"label": "Item1"
},
{
"id": 2,
"label": "Item2"
},
{
"id": 3,
"label": "Item3"
}
];
var value = 2;
var result = items.filter(function(x) {
return x.id === value;
});
console.log(result); // Prints an Array of object.
Try this
var obj = {} ;
items = [
{ "id": 1, "label": "Item1" },
{ "id": 2, "label": "Item2" },
{ "id": 3, "label": "Item3" }
];
items.map(function(n) { obj[n.id] = n });

Categories

Resources