I try to merge an array of objects into a single string, but got a bit lost. The input looks like that:
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
Expected Output:
"title: Example Text title, description: Example Text description, video: Example Text video"
Thanks for any hint.
Since you want a single string out of this, and not an array, you will want to use Array.forEach to concatenate onto an existing string object, like so:
let outStr = '';
array.forEach((ele, idx) =>
outStr += `${ele.key}: ${ele.text}${idx < array.length ? '' : ', '}`
);
You could also use Array.map like the folks in the comments above suggested, but you will need to join the result to produce a single string at the end.
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
let result = "";
array.forEach((object, index) => {
result += `${object.key}: ${object.text}`
if(index < array.length - 1) {
result += ', ';
}
});
console.log(result);
I hope the following is useful for you.
const array = [
{
key: "title",
text: " Example Text title",
},
{
key: "description",
text: "Example Text description",
},
{
key: "video",
text: "Example Text video",
},
];
array.map(item => `title: ${item.text}, description: ${item.text}, video: ${item.text}`).toString()
//'title: Example Text title, description: Example Text title, video: Example Text title,title: Example Text description, description: Example Text description, video: Example Text description,title: Example Text video, description: Example Text video, video: Example Text video'
Related
I have an array in which I have some string value holding the id along with answer selected and I have different object in which I have the detail about answer which is selected. The below array keep updated whenever we select an option from question.
arr = ["Q1A1", "Q2A3"]
assume Q1 is Question no. 1 and A1 is option selected from the question. And below I have an object for the corresponding Q1 which contained the detail about answers and this object also get change as we move over to Q2
{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}
]
}
same way I have any another object for Q2 if we select the answer in Q1, now we have different object for Q2
{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}
]
}
I need to lookup the object with the help of array which contain question and answer(eg, "Q1A1") with selected and need to find the text for answer selected i.e ("Yes") if u look into the above object for question 1. Hence I need put into the array like this way.
result = ["Q1_Yes","Q2_Test3"]
This code will help you to get those results.
let selected = ["Q1A1", "Q2A3"];
let QA = [
{
id: "Q1",
answers: [
{
id: "Q1A1",
text: "Yes"
},
{
id: "Q1A2",
text: "No"
}
]
},
{
id: "Q2",
answers: [
{
id: "Q2A1",
text: "Test 1"
},
{
id: "Q2A2",
text: "Test 2"
},
{
id: "Q2A3",
text: "Test 3"
},
{
id: "Q2A4",
text: "Test 4"
}
]
}
];
let all_answers = QA.reduce((allanswers,qa)=>(qa.answers.map(d=> allanswers[d.id]=[qa.id,d.text]),allanswers),{});
const result = selected.map(selected => all_answers[selected].join('_'))
console.log(result)
I need a little help with a loop in JavaScript.
Please see the JSON data below
{
"blogs":{
"id1":{
"title":"Title 1",
"date":"test_date",
"datestamp":"test_datestamp 1",
"content":"The content",
"url":"https:\/\/www.testlink1.com",
"tags":["move","New"]
},
"id2":{
"title":"Title 2",
"date":"test_date",
"datestamp":"test_datestamp 2",
"content":"The content 2",
"url":"https:\/\/www.testlink2.com",
"tags":["Netherlands","Yellow"]
}
}
}
Next I parse the JSON like below
data = JSON.parse(this.response); //This JSON is the result from an AJAX call to a PHP file
For using the data I do this
for(let id in data.blogs){
console.log(data.posts[id].date);
console.log(data.posts[id].title);
//etc.
}
But how can I loop the tags array inside this loop?
I tried this but with no result
for(let id in data.blogs){
for(let tag in data.blogs.tags){
alert(data.blogs[id].tags[tag]);
}
}
Who can help me with this?
But how can I loop the tags array inside this loop?
You need to identify the blog item currently in the process loop.
Here due example, note the for-in as you wrote or the for-of loop to cycle the items.
const data = {
blogs: {
id1: {
title: 'Title 1',
date: 'test_date',
datestamp: 'test_datestamp 1',
content: 'The content',
url: 'https://www.testlink1.com',
tags: ['move', 'New']
},
id2: {
title: 'Title 2',
date: 'test_date',
datestamp: 'test_datestamp 2',
content: 'The content 2',
url: 'https://www.testlink2.com',
tags: ['Netherlands', 'Yellow']
}
}
}
for (const blogId in data.blogs) {
const blogItem = data.blogs[blogId]
console.log(`looping ${blogItem.title}`)
for (const tag of blogItem.tags) {
console.log(tag)
}
}
for (const blogItem of Object.values(data.blogs)) {
console.log(`looping ${blogItem.title}`)
for (const tag of blogItem.tags) {
console.log(tag)
}
}
I have a page that gets two arrays of input elements and sends them by post request to my app.js:
<input type="text" name="titleAttr[]" > </input>
<input type="text" name="descriptionAttr[]"> </input>
I created a Schema that receives an array with 2 fields, titleAttr and descriptionAttr, which correspond to the <input> elements above:
const mySchema = mongoose.Schema({
titulo: String,
attrs: [{
titleAttr: String,
descriptionAttr: String
}]
});
I can insert the data manually and it works:
MyModel.bulkWrite([ { insertOne : { document: {
title : "TEST",
attrs: [
{titleAttr : "test 1", descriptionAttr: "This is a test 1"},
{titleAttr: "test 2", descriptionAttr: "This is another test"}
]
} } }
]);
Here is a screenshot of the form .
When the post request is sent from my form and I print it in app.js, I get these results:
console.log(req.body.titleAttr); //result: [ 'test 1', 'test 2' ]
console.log(req.body.descriptionAttr);// result: [ 'This is a test 1', 'This is another test' ]
This code doesn't work:
ConceitoHTML.bulkWrite([ { insertOne : { document: {
titulo : req.body.title,
attrs: [
{
titleAttr: req.body.titleAttr,
descriptionAttr: req.body.descriptionAttr
}
]
} } } ]);
I want to merge my two arrays and insert into MongoDB as an array of objects. How do I generate an array like the following?
const myArray = [
{
titleAttr: req.body.titleAttr[0],
descriptionAttr: req.body.descriptionAttr[0]
},
{
titleAttr: req.body.titleAttr[1],
descriptionAttr: req.body.descriptionAttr[1]
}
]
You can do it with this code below 👇 to get an array as expected what you want:
const {titleAttr, descriptionAttr} = req.body;
const myArray = [];
// check the length first, make sure it's same
if(titleAttr.length === descriptionAttr.length) {
for(let i=0; i<titleAttr.length; i++) {
myArray.push({ titleAttr: titleAttr[i], descriptionAttr: descriptionAttr[i] })
}
}
console.log(myArray); // this is the array result
I hope it's can help you.
Let's say i have an array like:
array = [{
title: "foo1",
content: "bar1"
},{
title: "foo2",
content: "bar2"
},{
title: "foo3",
content: "bar3"
}];
Now i want to filter this array to have the objects that their title contains a character like '3'.
So now my filtered array should be
filteredArray = [{
title:"foo3",
content: "bar3"
}];
I've tried
filteredArray = $filter('filter')(array, {
title: "foo3"
});
But the problem with this is that title needs to be exactly "foo3". if i put "3" it won't filter that because it doesn't check if it contains it, it looks for an exact match.
Any ideas how to achieve this?
The filter filter (yeah, I know) does a contains filtering...
I pasted your code (working) into PLNKR and filtered on 3 and got back the title: 'foo3' element
array = [{
title: "foo1",
content: "bar1"
},{
title: "foo2",
content: "bar2"
},{
title: "foo3",
content: "bar3"
}];
$scope.filteredData = $filter('filter')(array, {
title: "3",
});
You would need to write your own filter. Check this answer on how to achieve what you want.
I am making an ajax call that returns some json data. I need to take this data, loop through it and build a new javascript array.
This is what the returned json looks like:
{
query: [ ],
products: 
[

{
title: "title 1",
price: "6.00",
magazine: "magazine name 1",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link1.php"
},

{
title: "title 2",
price: "6.00",
magazine: "magazine name 2",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link2.php"
},

{
title: "title 3",
price: "6.00",
magazine: "magazine name 3",
image: "/p/c/pc_90_cover.jpg",
type: "Magazine",
market: "Technology",
zinio: "http:www.zinio.com",
newsstand: "http://www.link3.php"
}
]
}
How do I loop through this data in javascript? This is what I have so far but it is very wrong! - apologies my javascript is not my strongest skill!
var allProducts = $.get("http://localhost:8888/imagine-publishing/web/app_dev.php/api/v1/search/search.json?query=pho", function(data) {
var arrProducts = [
for (var product in allProducts) {
title = product.title,
url = product.url,
label = product.title,
magazine = product.magazine,
image = product.imageThumb,
newsstand = product.newsstand,
googleplay = product.googleplay,
kindle = product.kindle,
barnesnoble = product.barnesnoble,
zinio = product.zinio,
kobo = product.kobo,
waterstones = product.waterstones,
type = product.type,
brandurl = product.brandurl
},
];
});
console.log(arrProducts);
Assuming the JSON is served with the correct Content-Type (application/json), jQuery will automatically parse the JSON and populate the first argument of the callback function with the result.
var arrProducts = data.products;
http://api.jquery.com/jQuery.parseJSON/
jQuery.parseJSON("json string")
Using jQuery's getJSON
http://api.jquery.com/jQuery.getJSON/
$.getJSON(url, function(data){
// Your code goes here
});