I have an array of products would like to add all the product information as an object to an empty array.
var data = {
"Vegetables": [
{
"id": "1",
"title": "Peas",
"type": "Green",
},
{
"id": "2",
"title": "Carrots",
"type": "root",
}
],
"Protein": [
{
"id": "3",
"title": "Steak",
"type": "Meat",
},
{
"id": "4",
"title": "Eggs",
"type": "Dairy"
}
]}
I am able to push just the title to the empty result array with the following:
function getCategory() {
result = [];
for (let item in data) {
data[item].forEach(v => result.push(v.title));
}
document.write(result);
}
getCategory();
But I would like to be able to push all the product information as an object so I can do some formatting. For example:
var myObj= "" ;
myObj = "<div class='box'>" + title +"<br> "+ type + "</div>";
result.push(myObj); // push it to result[]
I am unsure how to adapt the body of the for loop to accommodate my object:
data[item].forEach(v => result.push(v.title + v.type)); // needs to be pushed as object.
Any help appreciated.
Cheers
Related
I'm trying to filter some objects based on another array of objects. So I'm getting data from an API. These are for example receipts:
[
{
"id": 1,
"name": "test",
"category": {
"id": 1,
"name": "Cookies",
},
},
{
"id": 2,
"name": "test2",
"category": {
"id": 2,
"name": "Candy",
},
}
]
Then I'm trying to filter the objects on the category name based on another array of categories.
I've created a function for this:
function onSelectCategory(category) {
let receiptsList = receipts.filter((a) =>
a.category.includes(category.name)
);
setReceiptsView(receiptsList);
setSelectedCategory(category);
}
const category = [ { "id": 2, "name": "Candy" } ];
onSelectCategory(category);
When I run this function, I get an empty Array []. I can't really figure out what I'm doing wrong.
Since the param seems to be an array of objects, you need to use Array#some for comparison instead:
const receipts = [
{ "id": 1, "name": "test", "category": { "id": 1, "name": "Cookies" } },
{ "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];
const receiptsList = receipts.filter(({ category }) =>
categories.some(({ name }) => name === category.name)
);
console.log(receiptsList);
Another solution using Set:
const receipts = [
{ "id": 1, "name": "test", "category": { "id": 1, "name": "Cookies" } },
{ "id": 2, "name": "test2", "category": { "id": 2, "name": "Candy" } }
];
const categories = [ { "id": 2, "name": "Candy" } ];
const categorySet = new Set(categories.map(({ name }) => name));
const receiptsList = receipts.filter(({ category }) =>
categorySet.has(category.name)
);
console.log(receiptsList);
Assuming that category (the parameter) is a string, the issue is that you are attempting to get the attribute name from the string, when you should be comparing the string to the object.
Try this:
a.category.name == category;
instead of
a.category.includes(category.name)
I may be wrong aboout assuming that category is a string, please clarify by telling us what the parameter category is equal to.
I have a JSON in the following format and need to convert the 2 values into a Key / Value pair in javascript
"column_values": [
{
"id": "status",
"text": "Working on it"
}
]
I need the result to be
"column_values"[{"status": "Working on it"}]
I need the code to iterate through the column_values array and convert all the sets of id and text pairs to the key = id value : Value = text:values
Is my result possible?
Additional Information...
I am parsing a response from monday.com api in zapier.
the api payload is contained in
const results = response.json;
the full api payload is
{
"data": {
"boards": [
{
"name": "Test Board",
"items": [
{
"name": "Name Change",
"id": "625495642",
"column_values": [
{
"id": "person",
"text": ""
},
{
"id": "subitems",
"text": "Subitem 1, Subitem 2"
},
{
"id": "status",
"text": "Working on it"
},
{
"id": "dropdown",
"text": "Test1"
},
{
"id": "formula",
"text": ""
}
]
}
]
}
]
},
"account_id": 1111
}
I need to the the code to parse the data and replace the column_values with the format above, and then pass the reformated payload to
return results;
You just Map the Array you start out with to an Array with the values.
var column_values = [ { "id": "status", "text": "Working on it" } ]
var KeyValuePairs = column_values.map(cv => [cv.id,cv.text]);
console.log(KeyValuePairs);
If every object is going to contain the id and text keys only, you can map it and delete the other keys.
column_values = column_values.map(item => {
item[item.id] = item.text;
delete item.id;
delete item.text;
return item;
});
try this
var column_values = [ { "id": "status", "text": "Working on it" } ]
var res = column_values.map(x => ({[x.id] : x.text}))
console.log(res)
I have following array:
var array = [
{
"milestoneTemplate": {
"id": "1",
"name": "TEST1"
},
"id": "1",
"date": "1416680824",
"type": "ETA",
"note": "Note",
"color": "66FF33"
},
{
"milestoneTemplate": {
"id": "2",
"name": "Test 2"
},
"id": "2",
"date": "1416680824",
"type": "ATA",
"note": "Note 22",
"color": "66FF00"
}
];
And now i would like to check in forEach loop that object (which is passed in param of the function) is existing in array by his ID.
In case that not = do push into existing array.
arrayOfResults.forEach(function(entry) {
if(entry != existingInArrayByHisId) {
array.push(entry);
}
});
Thanks for any advice
You could create a helper function thats checks if an array contains an item with a matching property value, something like this:
function checkForMatch(array, propertyToMatch, valueToMatch){
for(var i = 0; i < array.length; i++){
if(array[i][propertyToMatch] == valueToMatch)
return true;
}
return false;
}
which you can then use like so:
arrayOfResults.forEach(function (entry) {
if (!checkForMatch(array, "id", entry.id)) {
array.push(entry);
}
});
I have been working on displaying values from a JSON feed and - with a great deal of thanks to help on the many previous posts I have read here - I can now write (display in browser) all the values of my objects in the main array BUT for the values of the 'name' objects which are 'nested' in an array > object > array > object > proprty:value structure (as below). Wondering if anyone might me kind enough to help me find a way to interate and display this level successfully - I feel I have run out of ideas on it at the moment :-(
Very thankful for an ideas. I have been using standard JavaScript not JQuery I should add.
var foo=[
{
"subjects":
[
"A1",
"SB2"
],
"title": "Box World",
"first_pub": "2013-12",
"characters":
[
{
"name":
{
"given": "Maxwell",
"honourific": "",
"family": "Smart"
},
"id": "MS34"
},
{
"name":
{
"given": "Samantha",
"honourific": "",
"family": "Stevens"
},
"id": "SS81"
} // end creators object 2
],
"publisher": "Galactic Publishing"
},
{
"subjects":
[
"A133",
"PB82"
],
"title": "Octonautica",
"first_pub": "2010",
"characters":
[
{
"name":
{
"given": "Peso",
"honourific": "Doctor",
"family": ""
},
"id": "MS34"
},
{
"name":
{
"given": "Barnacle",
"honourific": "Captain",
"family": ""
},
"id": "SS82"
}
],
"publisher": "Neptune House"
}
]
var obj_set = foo ;
for (var key in obj_set) {
document.write("\<h3\> Publication " + key + "\<\/h3\>" );
var obj = obj_set[key];
document.write("\<ol\>");
for (var prop in obj) {
document.write("\<li\>" + prop + " = " + obj[prop] + "\<\/li\>" );
}
document.write("\<\/ol\>");
}
//END MAIN KEY LOOP
Try this instead:
var i, j;
// iterate over main array foo
for (i=0; i<foo.length; i++) {
// iterate over characters array
for(j=0; j<foo[i].characters.length; j++) {
// each item contains an object "name"
var name = foo[i].characters[j].name;
console.log(name.honorific + ' ' + name.given + ' ' + name.family);
}
}
"category": [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}],
I have the above JSON parsed (using .ajax and jsonp as callback) and I would like to join all the values of "name" into a string. i.e. "Dogs, Cats, Sheep". How can I do this? I have tried simple join on "category" and name, i.e.
var cats = categories.join(", ");
OR
var cats = categories.name.join(", ");
But since we are looking at it's members and their string values, it doesn't work.
This looks like a job for $.map!
var data = {
"category": [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}]
}
var cats = $.map(data.category, function(v){
return v.name;
}).join(', ');
var text = "";
for(var i=0; category.length; i++)
{
text += category[i].name;
if(i!=category.length-1)
text += ", ";
}
Simpler, shorter version:
const category = [{
"id": 28,
"name": "Dogs"
},
{
"id": 14,
"name": "Cats"
},
{
"id": 878,
"name": "Sheep"
}]
let cats = category.map((item) => {
return item.name;
}).join(", ");
On the first part, the map function will return a string array with the contents item.name.
[ "Dogs", "Cats", "Sheep" ]
Since on arrays we have the ability to call join that will put all the items in array together but separated by whatever we pass to the join (in this case we have ", " it will separate by a comma and a space)
In the end we have:
Dogs, Cats, Sheep