How to create multi-dimentional array in Javascript? - javascript

I need to create an array like this:
events: [
id :'1',
title: 'All Day Event'
},{
id : '2',
title: 'some name'
},{
id: 999,
title: 'some title',
}]
I am executing this code inside a loop:
$events['title'] = 'hello';
$events['id'] = '1';
It's returning:
[ title: "hello", id: "1" ]
[ title: "hello", id: "1" ]
How can I change the code to meet my requirement?

Try:
var id1 = '1';
var title1 = 'All Day Event';
var events = [];
events.push({
id :id1,
title: title1
});
for a loop:
titles = ['All Day Event1','All Day Event2'];
ids = ['1','2'];//note both array need to have the same length
$.each(titles,function(i,v){
events.push({
id :ids[i],
title: titles[i]//or v
});
})

See some examples here and read some more about JSON
You need to iterate the JSON while adding dimensions and values in it

Related

How to Combine/merge two arrays in similar index of post request in node.js/express and convert in object to insert mongoose model

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.

Array.push not pushing properly

EDIT: I've added the res.send(json), wasn't included the snippet.
I'm trying to extract/scrape a website and combine their output into json data. However when I run the endpoint, the response combines every result into its key, instead of adding a record per iteration. To expound, I get:
{
item: "item1item2item3item4item5item6",
title: "title1title2title3title4title5title5",
price: "price1price2price3price4price5price6"
}
This is my target output format though..:
{ item: "item1",
title: "title1",
price: "price1",
itemlink: "itemlink1" },
{ item: "item2",
title: "title2",
price: "price2",
itemlink: "itemlink2" },
{ item: "item3",
title: "title3",
price: "price3",
itemlink: "itemlink3" }, etc...
Here's the below snippet:
request(url, function(error, response, html){
if(!error){
var $ = cheerio.load(html);
var json = [];
/* Pulls out all the titles
$('.item-name').each(function() {
var title = $(this).text();
json2.push({title: title});
})
*/
function getID(str) {
return str.split('viewitem.php?iid=')[1];
}
$('.catlist').each(function(key, index) {
var title = $('.item-name').text();
var price = $('.catprice').text();
var id = getID($('h2').children().attr('href'));
var itemlink = $('h2').children().attr('href');
json.push({
id: id,
title: title,
price: price,
itemlink: itemlink
});
})
}
res.send(json)
})
I'm out of my wits, already spent hours on this. Any idea why they are not iterating properly for me? Thanks in advance!
$('.catlist').each(function(key, index) {
var title = $(this).find('.item-name').text();
var price = $(this).find('.catprice').text();
var id = getID($(this).find('h2').children().attr('href'));
var itemlink = $(this).find('h2').children().attr('href');
var temp =
{
id: id,
title: title,
price: price,
itemlink: itemlink
};
json.push(temp);
})
You need to find children for each .catlist and push them to array one by one
As you can see in your code you are assigning value to json in every iteration. So that's why it's not adding new record to it.
Have a look to this code
$('.catlist').each(function(key, index) {
var title = $('.item-name').text();
var price = $('.catprice').text();
var id = getID($('h2').children().attr('href'));
var itemlink = $('h2').children().attr('href');
var temp =
{
id: id,
title: title,
price: price,
itemlink: itemlink
};
json.push(temp);
})
Try this
json.push( {
id: id,
title: title,
price: price,
itemlink: itemlink
});

Filter an array of objects by a property containing a substring in AngularJS

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.

Dynamically add attributes as object properties

I'm working on bootstrap-multiselect, I'm trying to add data attributes in the dataprovider method.
Current
var options = [
{label: 'Option 1', title: 'Option 1', value: '1', selected: true},
{label: 'Option 2', title: 'Option 2', value: '2'}];
In the code it maps these an <option> tag like so:
$tag = $('<option/>').attr({
value: option.value,
label: option.label || option.value,
title: option.title,
selected: !!option.selected,
disabled: !!option.disabled
});
Desired
var options =[
{
"label": "Item 1",
"value": 1,
"selected": false,
"attributes": [
{
"some-attribute": 10001
},
{
"another-attribute": "false"
}
]
}
]
So it will render on the HTML element as data-some-attribute="10001" data-another-attribute="false".
I started out adding this to the code (which I know won't work):
$tag = $('<option/>').attr({
value: option.value,
label: option.label || option.value,
title: option.title,
selected: !!option.selected,
disabled: !!option.disabled,
forEach(option.attributes, function(attribute){
})
});
The problem of course is you can't add a loop as an objects properties.
Once this is working I can add a pull request to the repository. I did ask a question on the repo but decided to try and tackle it myself Issue #592
Any ideas?
I would suggest changing attributes from an array to an object, since attribute names should be unique. It also simplifies how you would get the data attributes on the element.
var attributes = {
value: option.value,
label: option.label || option.value,
title: option.title,
selected: !!option.selected,
disabled: !!option.disabled
};
for (key in option.attributes) {
attributes['data-' + key] = option.attributes[key];
}
$tag = $('<option/>').attr(attributes);
If you wanted to keep it as an array, you can do the following:
var attributes = {
value: option.value,
label: option.label || option.value,
title: option.title,
selected: !!option.selected,
disabled: !!option.disabled
};
for (var i = 0; i < option.attributes.length; i++) {
var key = Object.keys(option.attributes[i])[0],
val = option.attributes[i][key];
attributes['data-' + key] = val;
}
$tag = $('<option/>').attr(attributes);
Doing this, however, provides no benefit and introduces complexity. If each object can have multiple keys, the code will need to change further.
You need to create the element first then add the attributes to it.
So your code should be like this:
var options = [{
"label": "Item 1",
"value": 1,
"selected": false,
"attributes": [{
"some-attribute": 10001
}, {
"another-attribute": "false"
}]
}]
console.log(options.length);
$.each(options, function(option) {
var $tag = $('<option/>').attr({
value: options[option].value,
label: options[option].label || options[option].value,
title: options[option].title,
selected: options[option].selected,
disabled: options[option].disabled
});
console.dir(option);
$.each(options[option].attributes, function(att) {
$tag.attr("data" + Object.keys(att)[0], att[0])
});
$("#mySelect").append($tag);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
</select>

how to Dynamically generate JSON in a loop with Js?

I'm making a project with PebbleJS.
i'm a noob and i'm learning little by little..so after recieving a JSON from a webpage and put all the data in localStorage objects, i want to put my variables in a UI.Menu Window, which is basically a JSON variable as you can see in example below:
var main = new UI.Menu({
sections: [{
items: [
{
title: 'street name a',
subtitle: 'ID 1121'
}, {
title: 'street name b',
subtitle: 'ID 1431'
}, {
title: 'street name c',
subtitle: 'ID 1907'
},{
title: 'street name d',
subtitle: 'ID 1002'
},{
title: 'street name e',
subtitle: 'ID 1330'
},
]
}]
});
i tried to make a loop cycle inside but gives me error...(pseudocode)
for (var x=0;x<10;x++)
{
title: localStorage.title+x,
subtitle: 'ID '+localStorage.title+x
}
i need to make this with no jQuery or other JS Frameworks, only pure javascript...
if i understand you question correctly, you want to create the data-structure from your first code example through a loop.
the data structure is a object with some properties and sub-objects like arrays. the structure just defines objects in your code. there is no json involved.
json is a subset of javascript which is used to interchange data-structures. it consists of plain text files with just javascript object declarations and is usually parsed to create a data-structure in memory. by declaring your data-structure in code there is no need to use an additional json-parsing step.
to setup the initial structure as above you would do:
var data = {
sections: [
{
items: []
}
]
}
than you would get the items array:
var items = data.sections[0].items
to this array you can add the items with your loop:
for ( var x = 0; x < 10; x++ ) {
var item = {
title: localStorage.title + x,
subtitle: 'ID ' + localStorage.title + x
};
items.push(item);
}
now you can build your UI.Menu with the data-object.
var main = new UI.Menu(data)

Categories