How to get the length of an object array object in angular - javascript

How to get the length of an object array object in angular.
Here's the code:
list.component.ts
const obj: any = {};
this.days.forEach((x: any) => {
const itemFilter = this.rowData.filter((item: any) => item);
itemFilter.forEach((item: any) => {
const date = format(item.lastpmdate, 'YYYY-MM-DD');
if (format(x.date, 'YYYY-MM-DD') === date) {
if (obj[date]) {
obj[date].push(item);
} else {
obj[date] = [item];
}
}
});
});
What I need is to get the length of the object array.
Thanks in advance.

You can list the keys of the target object with Object.keys and then check its length as a normal array:
Object.keys(this.days).length
If you have an object of arrays:
Object.values(this.days).map(v => v.length)
Object.values() allows to iterate over the object values instead of the keys.
Having these, you can then get the length for each of the inner arrays.

Related

How to convert json object keys into different arrays removing the duplicate

I'm having the JSON like this i need to group this JSON with all the keys in JSON object and value should in array (excluding duplicates).
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
My output should be like
{"sex":["Male","Female"],"name":["Jeff","Megan","Taylor","Madison"]}
how we can able to achieve this
function getValues(array) {
var result = {};
array.forEach(obj => {
Object.keys(obj).forEach(key => {
if(!Array.isArray(result[key]))
result[key] = [];
result[key].push(obj[key]);
})
})
return result;
}
You could use the Array.reduce() method to transform your array into a single object:
var people = [
{sex:"Male", name:"Jeff"},
{sex:"Female", name:"Megan"},
{sex:"Male", name:"Taylor"},
{sex:"Female", name:"Madison"}
];
const transformed = people.reduce((acc, e) => {
Object.keys(e).forEach((k) => {
if (!acc[k]) acc[k] = [];
if (!acc[k].includes(e[k])) acc[k].push(e[k]);
});
return acc;
}, {});
console.log(transformed);
If for one of the object keys (sex or name in this case) a value array does not exist, it is created. Before a value is pushed into any of the value arrays, it is verified that it is not already present in that array.

Return array of values from object based on array

I have an object that looks like this
I would like to return an array of wsnames based on altnames. For example, I provide an array ["AAVEETH", "AAVEXBT"] and get back ["AAVE/ETH", "AAVE/XBT"].
I figured out how to use lodash __.filter like this
const wsnames = _.filter(
obj,
(item) => item.altname === 'AAVEETH' || item.altname === 'AAVEXBT'
)
but this only returns the full object entry. Also, my input array won't be known beforehand.
First turn the values of the object into an array of values with Object.values(). Now you can use array methods like filter to filter out the unwanted values and map to create a new array with only the wsname properties.
const wsNames = Object.values(obj)
.filter(({ altname }) => altname === 'AAVEETH' || altname === 'AAVEXBT')
.map(({ wsname }) => wsname);
Now you can turn this logic into a function in which you pass the object you want to filter from and an array of altname values that you want to get the wsname values from.
const getWsNames = (obj, altNames) => Object.values(obj)
.filter(({ altname }) => altNames.includes(altname))
.map(({ wsname }) => wsname);
const wsNames = getWsNames(obj, ['AAVEETH', 'AAVEXBT']);
You can just use Object.values and array.filter to achieve this.
let arr = ["AAVEETH", "AAVEXBT"]
let masterObj = [....] // your object having all data
result = []
arr.forEach(i => {
let found = Object.values(masterObj).filter(i => i.altname)[0]
if(found){
result.push(i.wsname)
}
})
In above code i am just looping on your altname array on behalf of which you want to get wsname array and in that i am using object.values to get all values as array and then i am doing filteration to get the wsname of the matching object that have matching altname

while pushing the data in to arrays, not added in order

enter image description here
i need to push the data one after another, but here i am getting to add in disorder like last added array in to first.
for (var key in data[tabName + scoreBreakDown]) {
var values = data[tabName + scoreBreakDown][key];
var staticData = values[0];
var obj = [];
obj.push(staticData.CompanyName);
obj.push(staticData.Country_ORIG);
for (var value in values) {
if (addHeader) {
headersArray.push(values[value].AspectName);
weightArray.push(values[value].ScoreWeight);
}
obj.push(values[value].SPESGScore_ORIG);
}
addHeader = false;
dataArray.push(obj);
}
You can use array.map to map through an array and transform it into a new array in order.
In this example, we are just multiplying each value by 3, but the transformation is arbitrary.
let loop = (arr) => {
return arr.map(item => {
return item*3
})
}
console.log(loop([1,2,3,4,5]))
If you want to loop through an object in order this way, you can use Object.keys() this will return an array of the keys in the object.
let loop = (obj) => {
return Object.keys(obj).map(item => {
return `${item}: ${obj[item]}`
})
}
let obj = {
first_name:"John",
last_name:"Doe",
age:23
}
console.log(loop(obj))
So instead of using a for loop and an if statement to check a condition and push the data to the array after each iteration, you can use something Array.filter() to remove entries you don't want to push, and return them in order.
data = [
{header:true, value:"item1"},
{header:false, value:"item2"},
{header:true, value:"item3"},
]
let array = data.filter(item => {return item.header}).map(item => {
return item.value
})
console.log(array)

Js: How can i convert an Object property name to a string

I want to iterate through an object and get the property names so i can use them to retrieve a localstored item.
for (var property in parts) {
if (parts.hasOwnProperty(property)) {
var item = localStorage.getItem(property);
console.log(item);
}
}
how can i achieve this ?
You can get all object keys as array of strings via Object.keys(object), and then iterate through this array with any iteration method for arrays, for example, let's use forEach:
const obj = {
one: true,
two: 2,
three: 'Value three'
}
const keys = Object.keys(obj);
keys.forEach(key => {
console.log('Current key:', key);
//const item = localStorage.getItem(key);
})

JavaScript or Lodash find objects by key

In an array of objects with diff keys, how do I find objects by key using ES6 or Lodash?
const arr = [{a:2}, {b:3}, {fred:10}]
I want the result to be:
=> [{a:2}, {fred:10}]
I don't want to use an omit style approach.
const filtered = arr.filter(obj => obj.hasOwnProperty("a") || obj.hasOwnProperty("fred"));
// or, if you have dynamic / lots of keys:
const keys = ["a", "fred"];
const filtered = arr.filter(obj => keys.some(key => obj.hasOwnProperty(key));
filter method will be useful. Create a function and pass an array of keys. Inside filter function check if the key is matching with the parameter array. If it passed then return that object
var orgObject = [{
a: 2
}, {
b: 3
}, {
fred: 10
}];
function searchByKey(keyNames) {
return orgObject.filter(function(item) {
for (var keys in item) {
if (keyNames.indexOf(keys) !== -1) {
return item
}
}
})
}
console.log(searchByKey(['a', 'fred']))
Basically you want all the objects from the array who have the fields a or fred. You can use the hasOwnProperty() on the objects while filtering.
_.filter(array, elem => elem.hasOwnProperty('a') || elem.hasOwnProperty('fred'));

Categories

Resources