"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
Related
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)
Here is a JSON array below.
let data = {
"list": [
{ "name": "my Name", "id": 12, "type": "car owner" },
{ "name": "my Name2", "id": 13, "type": "car owner2" },
{ "name": "my Name4", "id": 14, "type": "car owner3" },
{ "name": "my Name4", "id": 15, "type": "car owner5" }
]
}
Now as i want to access the "name" in the above JSON list here is my approach so far below.
console.log(data.list.filter(record => record.name.match(/my Name2.*/)));
Now i want to pass a dynamic variable in between the /my Name2.*/ how can i do that.
Suppose i want to pass let str = 'my Name' like this way /str.*/ how is it possible and i want to only get the list array of "name" only rather than whole bunch of existing properties like id and type.
To use a variable inside of a regular expression, use the RegExp constructor. Then you can use map to keep only the names:
/* Same data as yours */ const data = {list:[{name:"my Name",id:12,type:"car owner"},{name:"my Name2",id:13,type:"car owner2"},{name:"my Name4",id:14,type:"car owner3"},{name:"my Name4",id:15,type:"car owner5"}]};
const str = "my Name2";
const regex = new RegExp(str + ".*");
const res = data.list
.filter(record => record.name.match(regex))
.map(record => record.name);
console.log(res);
let data = {
"list": [
{ "name": "my Name", "id": 12, "type": "car owner" },
{ "name": "my Name2", "id": 13, "type": "car owner2" },
{ "name": "my Name4", "id": 14, "type": "car owner3" },
{ "name": "my Name4", "id": 15, "type": "car owner5" }
]
}
let input='my Name'
console.log(data.list.filter(record => record.name===input).map(record=>record.name));
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
I have 2 json format, namely jsonA and jsonB, in which i would like to combine into jsonC as follow.
Appreciate if someone can tell me how to do it.
jsonA
{
"text1": "Hello",
"text2": "Hi",
"text3": "There"
}
jsonB
[
{
"id": "text1",
"category": "Big"
},
{
"id": "text2",
"category": "Medium"
},
{
"id": "text3",
"category": "Small"
},
]
Final
[
{
"id": "text1",
"category": "Big",
"message": "Hello"
},
{
"id": "text2",
"category": "Medium",
"message": "Hi"
},
{
"id": "text3",
"category": "Small",
"message": "There"
}
]
Solution for a new array.
Basically it iterates the array and build a new object for every found object. It adds a new property message with the wanted content form objectA.
var objectA = { "text1": "Hello", "text2": "Hi", "text3": "There" },
objectB = [{ "id": "text1", "category": "Big" }, { "id": "text2", "category": "Medium" }, { "id": "text3", "category": "Small" }],
objectC = objectB.map(function (a) {
return {
id: a.id,
category: a.category,
message: objectA[a.id]
};
});
document.write('<pre>' + JSON.stringify(objectC, 0, 4) + '</pre>');
Soulution for a mutated array.
This solution takes the array and adds in the loop a new property with the value from objectA.
var objectA = { "text1": "Hello", "text2": "Hi", "text3": "There" },
objectB = [{ "id": "text1", "category": "Big" }, { "id": "text2", "category": "Medium" }, { "id": "text3", "category": "Small" }];
objectB.forEach(function (a) {
a.message = objectA[a.id];
});
document.write('<pre>' + JSON.stringify(objectB, 0, 4) + '</pre>');
Firstly, You need to traverse 2nd json array. Than traverse 1st json and compare for indexing. If indexing matches then add new attribute to 2nd json.
Here is full example :
var jsonA = '{"text1": "Hello","text2": "Hi","text3": "There"}';
var jsonB = '[{"id": "text1","category": "Big"},{"id": "text1","category": "Medium"},{"id": "text1","category": "Small"}]';
jsonA = JSON.parse(jsonA);
jsonB = JSON.parse(jsonB);
for(var i=0;i<jsonB.length;i++){
for(var j in jsonA){
if(j == ("text"+(i+1))){
jsonB[i].message = jsonA[j];
}
}
}
console.log(JSON.stringify(jsonB));
Output : [{"id":"text1","category":"Big","message":"Hello"},{"id":"text1","category":"Medium","message":"Hi"},{"id":"text1","category":"Small","message":"There"}]
I have an array of objects. I would like to reformat into a new array but am not sure how to begin. I have jQuery and Underscore available.
Here is my original array:
var myArray = [
{
"name": "Product",
"value": "Car"
},
{
"name": "Product",
"value": "Boat"
},
{
"name": "Product",
"value": "Truck"
},
{
"name": "Color",
"value": "Blue"
},
{
"name": "Location",
"value": "Store"
}
];
Here is what I am trying to make the new Array look like:
var newArray = [
{
"name": "Product",
"value": "Car Boat Truck"
},
{
"name": "Color",
"value": "Blue"
},
{
"name": "Location",
"value": "Store"
}
];
In the newArray the Products are all in one object.
You can use the groupBy method to get all the elements with the same name together, then map to transform them into what you want. And pluck is useful here to combine the values in the output array.
Here's quick, simple solution:
var newArray = _.chain(myArray)
.groupBy("name")
.map(function(a) {
return {
"name": a[0].name,
"value": _.pluck(a, "value").join(" ")
};
})
.value();
Demonstration
And just for completeness, here's the non-chained version:
var newArray = _.map(_.groupBy(myArray, "name"), function(a) {
return {
"name": a[0].name,
"value": _.pluck(a, "value").join(" ")
};
});
Here's a more generalized solution that's reusable and not hard-coded. This way, you can create multiple groupBy methods for different properties of different object collections, then join the properties that you require. jsFiddle
function groupBy(groupBy) {
return function(source, joinOn) {
return _.each(_.groupBy(source, groupBy), function(val, key, context){
context[key] = _.pluck(val, joinOn).join(' ');
});
};
}
var groupByNameOn = groupBy('name');
console.log(groupByNameOn(arr, 'value'));