how to count value in object javascript - javascript

hay , i have JSON format like this from looping
let data = {
status: "0"
description: "item 1"
}
{
status: "1"
description: "item 1"
}
i want to get value status and count how many status with value 0
expected output like this :
let gg = "status 0 as much 1"
how to do this in javascript ? thanks

First your JSON is invalid. Possibly what you want is an array that contains objects that you can iterate over. You need to quote your data properly, and include commas where they're required.
'[{ "status": "0", "description": "item 1" }, { "status": "1", "description": "item 1" } ]'
Once you have valid JSON and you've parsed it you can iterate over the objects.
Here's a function that passes in the parsed data, and the desired property and value as arguments. It filters out the objects that match the condition, and returns a string with the details.
const data = [{ status: '0', description: 'item 1' }, { status: '1', description: 'item 1' }, { status: '0', description: 'item 1' } ];
function getStatus(data, type, value) {
// `filter` out the objects where the property key matches the value
const out = data.filter(obj => obj[type] === value);
// Return a template string with the details
return `status ${value} as much ${out.length}`;
}
console.log(getStatus(data, 'status', '0'));

You missed some commas but I think you want something like
Edited
If you are trying to extract this from an object with property keys you should use..
Object.values(obj).reduce((acc, cur) => !cur.status ? acc + 1 : acc, 0)
If it's an array
arr.reduce((acc, cur) => !cur.status ? acc + 1 : acc, 0)
Like others have said the object in the question is not valid

Related

How do I populate an array of objects where every object has an array inside of it using response from rest API?

I can't google the right solution for this for about an hour straight,
So I'm getting a response from the API that looks like this:
[
{
"Name": "name1",
"Title": "Name One",
"Children": [
{
"Name": "Name 1.1",
"Title": "Name one point one"
},
]
And I need it to fit this kind of "mold" for the data to fit in:
{
title: 'Name One',
value: 'name1',
key: '1',
children: [
{
title: 'Name one point one',
value: 'Name 1.1',
key: 'key1',
},
I am trying to achieve this using a foreach but It's not working as intended because I need to do this all in one instance of a foreach.
Here's what I gave a go to(vue2):
created() {
getData().then(response => {
const formattedResponse = []
response.forEach((el, key) => {
formattedResponse.title = response.Title
formattedResponse.name = response.Name
formattedResponse.children = response.Children
})
})
Use map over the main array and use destructuring assignment to extract the properties by key, and relabel them, and then do exactly the same with the children array. Then return the updated array of objects.
const data=[{Name:"name1",Title:"Name One",Children:[{Name:"Name 1.1",Title:"Name one point one"}]},{Name:"name2",Title:"Name Two",Children:[{Name:"Name 1.2",Title:"Name one point two"}]}];
const result = data.map((obj, key) => {
const { Title: title, Name: value } = obj;
const children = obj.Children.map(obj => {
const { Title: title, Name: value } = obj;
return { title, value, key: (key + 1).toString() };
});
return { title, value, children };
});
console.log(result);
Your API response is JSON. All you need to do is:
var resp=JSON.parse(API response);

How to filter array of objects and check if more than one object inside the array has the same property value in Javascript?

How to filter the array of objects and check if more than one object inside the array has the same property value plan "enterprise" in Javascript.
this.accounts
.filter(
item => item.plan === 'enterprise'
)
// then how can I check if there is more than one object
// containing above enterprise value? if so then return some message.
}
How above filtering can be continued for achieving the result?
You can get the length of the array and then check if it is greater than one, hence print a message
const elmCount = this.accounts
.filter(
item => item.plan === 'enterprise'
).length
if (elmCount > 1) {
console.log('print message')
}
After you have perform the filter you can just count the number of items in the result of the filter method. which will tell you how many accounts with enterprise plan exists
var accounts = [
{id: 1, name: "Account 1", plan: "basic"},
{id: 2, name: "Account 2", plan: "medium"},
{id: 3, name: "Account 3", plan: "enterprise"},
{id: 4, name: "Account 4", plan: "medium"},
{id: 5, name: "Account 5", plan: "enterprise"}
]
var enterpriseAccounts = accounts.filter(item => item.plan === "enterprise");
if(enterpriseAccounts.length > 1 ) {
console.log('There are more than one enterprise account');
} else {
console.log('There are 0 or 1 enterprise account');
}
Just filter and then get the length.
accounts = [{plan: 'test'}, {plan: 'extra'}, {plan: 'enterprise'}, {plan: 'basic'}, {plan: 'enterprise'}];
let length = accounts.filter(item => item.plan === 'enterprise').length;
if (length>1) console.log('enterprise more than once: ' + length);

Loop through and delete elements in an array of objects

In my Vue.js project I have an array of objects which I want to list through and display in the browser.
My array contains four objects, I want to display only 3. The way I choose the 3 objects are dependent on a preference setting that the user has chosen somewhere else in the project and stored in a variable (below it is called userPreference). I am currently stuck on the best and most efficient way to remove one of the objects from my array based on the userPreference value.
My v-for in my template
<ul v-for="item in getOutroItems"><li>item<li></ul>
My object:
data() {
return {
outroItems: [{ title: "outro1", text: "XYZ" }, { title: "outro2", text: "ABC" }, { title: "outro3",
text`enter code here`: "QRS" }, { title: "outro4", text: "TUV" }],
userPreference: ""
};
}
My computed property (this is what I have so far)
getOutroItems() {
this.outroItems.filter((value) => {
if(this.userPreference === "newsletter") {
/// here I want to remove outro2 from my array and return an array with the other 3 values
} else (this.userPreference === "noNewsletter") {
/// here I want to remove outro3 from my array and return an array with the other 3 values
}
})
}
So, what is the best way to remove a specific element from an array?
Thanks in advance, and let me know if anything wasn't clear enough.
Your requirement can be fulfilled by below code as array.filter just wants true or false in its return to accept or remove an element from its array.
getOutroItems() {
this.outroItems.filter((value) => {
if(this.userPreference === "newsletter") {
// here I want to remove outro2 from my array and return an array with the other 3 values
return value.title != 'outro2';
} else (this.userPreference === "noNewsletter") {
// here I want to remove outro3 from my array and return an array with the other 3 values
return value.title != 'outro3';
}
})
}
However if you want to not create another array if it is big. you should go with swapping such elements to be removed with the end indexed element in the array and popping those many elements from the array.
There are multiple ways of getting the correct items from an array.
My preferred method and in your example: Using array.filter
const outroItems = [
{ title: "outro1", text: "XYZ" },
{ title: "outro2", text: "ABC" },
{ title: "outro3", text: "QRS" },
{ title: "outro4", text: "TUV" }
];
const leftOverItems = outroItems.filter((item) => item.title !== "outro2");
console.log(leftOverItems);
Another option is to find the index of the item to remove and then remove it with splice
const outroItems = [
{ title: "outro1", text: "XYZ" },
{ title: "outro2", text: "ABC" },
{ title: "outro3", text: "QRS" },
{ title: "outro4", text: "TUV" }
];
const itemToDelete = outroItems.find((item) => item.title === "outro2");
const indexToDelete = outroItems.indexOf(itemToDelete);
outroItems.splice(indexToDelete, 1);
console.log(outroItems);
Combining any of the functions above with a function will prevent you from writing duplicate code.
const itemToRemove = (arr, attr, name) => {
return arr.filter((item) => item[attr] !== name);
}
const outroItems = [
{ title: "outro1", text: "XYZ" },
{ title: "outro2", text: "ABC" },
{ title: "outro3", text: "QRS" },
{ title: "outro4", text: "TUV" }
];
// Remove from "outroItems" where "title" is "outro2"
const removed2 = itemToRemove(outroItems, "title", "outro2");
// Remove from "outroItems" where "title" is "outro3"
const removed3 = itemToRemove(outroItems, "title", "outro3");
// Remove from "outroItems" where "text" is "TUV"
const removedTUV = itemToRemove(outroItems, "text", "TUV");
console.log(removed2);
console.log(removed3);
console.log(removedTUV);

JavaScript | Spread operator update nested value

I am trying to update a nested value of an object using the spread operator. This is my first time using this and I believe I am pretty close to achieving my end goal but I just can't seem to figure out what I actually need to do next.
I have an array which is structured like this:
[
{
name: "Category 1",
posts: [
{
id: 1,
published: false,
category: "Category 1"
},
{
id: 2,
published: true,
category: "Category 1"
}
]
},
{
name: "Category 2",
posts: [
{
id: 3,
published: true,
category: "Category 2"
},
{
id: 4,
published: true,
category: "Category 2"
}
]
}
]
On the click of a button I am trying to update the published value, and as I am using React I need to set the state. So it got recommended to me that I update using the spread operator.
onPostClick(post) {
post.pubished = !post.published;
this.setState({...this.state.posts[post.category], post})
}
If I log out the result of {...this.state.posts[post.category], post} I can see that the published is getting added to the parent which forms:
{
name: "Category 1",
published: false,
posts: [
...
]
}
Obviously this isn't the intended result, I want it to update the actual object within the posts object.
I have tried to do something like this.setState({...this.state.posts[post.category].posts, post}) but I get a message that it is undefined.
You can't access your data with this.state.posts[post.category]. posts data in the objects of the array.
You can make a filter to find your category object in array and change its posts value.
onPostClick(post) {
//CLONE YOUR DATA
var postArray = this.state.posts;
//FIND YOUR CATEGORY OBJECT IN ARRAY
var categoryIndex = postArray.findIndex(function(obj){
return obj.name === post.category;
});
//FIND YOUR POST AND CHANGE PUBLISHED VALUE
postArray[categoryIndex].posts.forEach(function(item){
if (item.id === post.id) {
item.published = !item.published;
}
});
//SET TO STATE TO RERENDER
this.setState({ posts: postArray});
}
This should work if your name of the state is true.
just adding, we know there are many ways to succeed, maybe you also want to try this way too..
onPostClick = post => {
let published = this.state.data.map((item, i) => {
item.posts.map((item_post, i) => {
if (item_post.category === post.category) {
item_post.published = !post.published;
}
});
});
this.setState({ ...this.state.data, published });
};

Spread values after certain index

I am trying to spread array values into an object after a certain index 3 (column_4).
const array = ['Column_5', 'Column 6', 'Column 7']
const object = {
column_1: '',
column_2: 'Status',
column_3: 'Master',
column_4: 'Locale',
...array
}
At the moment, Column 5/6/7 appear at the start:
{
0: "Column_5",
1: "Column 6",
2: "Column 7",
column_1: "",
column_2: "Status",
column_3: "Master",
column_4: "Locale"
}
But I need them to appear in numerical order. Any ideas? I've tried using Ramda's insert method without any success.
const array = ['column_5', 'column_6', 'column_7']
const object = {
column_1: '',
column_2: 'Status',
column_3: 'Master',
column_4: 'Locale',
...array.reduce((acc, item) => {
acc[item] = item;
return acc;
}, {}),
}
console.log(object);

Categories

Resources