I need to add options to a drop down list. I have an array with the options that I need in the drop down list, but I'm not sure how to append the array to the list
var productList = document.getElementById("selectFood");
var foodOption = document.createElement("option");
foodOption.textContent = [{
option1: "Meat Lovers"
}, {
option2: "Buffalo Wings"
}, {
option3: "margherita"
}, {
option4: "classic"
}];
for (i = 0; i < productList.length; i++) {
productList.appendChild(foodOption);
}
you can do with jquery,
$.each(foodOption.textContent, function (i, value) {
$('#selectFood').append($('<option>').text(value).attr('value',value));
});
You need to create an option element.
for (i = 0; i < foodOption.textContent.length; i++) {
var newElement = document.createElement('option');
newElement.innerHTML = foodOption.textContent[i];
productList.appendChild(newElement);
}
You have to make an array of string rather than array of objects
try this
foodOption.textContent = ["Meat Lovers" , "Buffalo Wings" , "margherita", "classic" ]
$.each(foodOption.textContent, function (index, value) {
$('#selectFood').append($('<option/>', { value: value, text: value }));
});
Try below code for your solution.
var productList = document.getElementById("selectFood");
var textContent = [{
option1: "Meat Lovers"
}, {
option2: "Buffalo Wings"
}, {
option3: "margherita"
}, {
option4: "classic"
}];
for(var iIntex in textContent) {
var foodOption = document.createElement("option");
var option=textContent[iIndex]["option"+(iIndex+1)];
foodOption.setAttribute("value",option);
foodOption.innerHTML=option;
productList.appendChild(foodOption);
}
Related
how to get the value in any way if key does match with "Item"
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
/* How to get value if index found by Item */
for(let i = 0; i<data.length; i++) {
console.log(data[i].includes("Item"));
//Expecting phone and case
}
for-in allows you to loop through the keys in an object. Not to be confused with for-of, which loop through elements in an array.
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
for(let datum of data)
{
for(let key in datum)
{
if(key.includes("Item"))
{
console.log(datum[key]);
}
}
}
In the simple way just change data[i].includes("Item") to data[i].keys().includes("Item").
BUT! Could we have some alternative data set here? For example:
const data = [{
"Item-55566": "phone",
"SomeKey: "Some Value",
123123: "Numeric key with value"
},
{
"Items-44555": "Case",
"Another-key": "Another value"
}
];
In this case you need to put some changes in your code to find correct keys & values:
for(let i = 0; i<data.length; i++) {
data[i].keys().forEach(v=>{
String(v).includes("Item") && console.log("Got index: ${i}, key: ${v}, value: ${data[i][v]}")
})
}
The for loop iterates through the two objects, so you can check to see whether the object has that particular property using hasOwnProperty()
const data = [
{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
},
];
/* How to get value if index found by Item */
for (let i = 0; i < data.length; i++) {
if (data[i].hasOwnProperty("Item-55566")) {
console.log(data[i]);
}
}
If you want to keep your loop (good that it's only one loop compared to other answers) you can do it with Object.keys and values:
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
/* How to get value if index found by Item */
for(let i = 0; i<data.length; i++) {
if(Object.keys(data[i])[0].includes('Item')){
console.log(Object.values(data[i])[0]);
}
}
You can use .filter to filter all items of the data array which includes Item text.
Then you can use .map to render new value from each object comes from data array.
const data = [
{"Item-55566": "phone", },
{ "Items-44555": "Case",},
{ "Other-44555": "Nope",}];
var filteredItems = data.filter(item => Object.keys(item)[0].includes("Item"));
console.log(filteredItems.map(item => Object.values(item)[0]));
Refactor code - By using .reduce()
const data = [
{"Item-55566": "phone", },
{ "Items-44555": "Case",},
{ "Other-44555": "Nope",}];
var res = data.reduce((prev, curr) =>
{
var entries = Object.entries(curr)[0];
if(entries[0].includes("Item"))
prev.push(entries[1]);
return prev;
}, []);
console.log(res);
I'm having an array of object,in which I'm storing the billkey and billvalue as attributes. I want billkey to be the key and billvalue to be the value of that particular key.
var log=[
{
billkey:"Name",
billvalue:"ABC"
},
{
billkey:"Department",
billvalue:"Computer"
}
{
billkey:"Name",
billvalue:"XYZ"
},
{
billkey:"Department",
billvalue:"Electrical"
}];
And I want to convert it into this format:
var log=[
{
Name:"ABC",
Department:"Computer"
},
{
Name:"XYZ",
Department:"Electrical"
}];
How about this simple solution. Hope it helps!
var log=[
{
billkey:"Name",
billvalue:"ABC"
},
{
billkey:"Department",
billvalue:"Computer"
},
{
billkey:"Name",
billvalue:"XYZ"
},
{
billkey:"Department",
billvalue:"Electrical"
}];
var arr = [];
var finalObj = [];
for(var i in log){
var someObject = log[i];
for(var j in someObject){
arr.push(someObject[j]);
}
}
for(var k = 0; k < arr.length; k+=4){
finalObj.push({
Name: arr[k+1],
Department: arr[k+3]
});
}
console.log(finalObj);
create the result using forloop
// store the values
var logs=[];
var log=[
{
billkey:"Name",
billvalue:"ABC"
},
{
billkey:"Department",
billvalue:"Computer"
},
{
billkey:"Name",
billvalue:"XYZ"
},
{
billkey:"Department",
billvalue:"Electrical"
},
];
loop the first array
for (i = 0; i < log.length; i++) {
// create empty variable for storing the values
var index = new Array();
// insert the first index value to key
index[log[i].billkey] = log[i].billvalue
// insert the second index value to key
index[log[i+1].billkey] = log[i+1].billvalue
// insert the result in to new array
logs.push(index);
// increment the i with 1
i=i+1;
}
console.log(logs);
You could use Array#reduce and use the remainder operator as witch for using either the last object or create a new one.
var log = [{ billkey: "Name", billvalue: "ABC" }, { billkey: "Department", billvalue: "Computer" }, { billkey: "Name", billvalue: "XYZ" }, { billkey: "Department", billvalue: "Electrical" }],
result = log.reduce(function (r, a, i) {
var o = {};
if (i % 2) {
r[r.length - 1][a.billkey] = a.billvalue;
} else {
o[a.billkey] = a.billvalue;
r.push(o);
};
return r;
}, []);
console.log(result);
I have a json array this way,
var simple = [];
for (var i = 0; i < 5; i++) {
simple.push({ id: id, name: name, mobile: mobile });
}
And the values from this json array is as below,
[{id:1
name:"Test"
mobile:100},
{id:2
name:"Test"
mobile:200},
{id:3
name:"Temp"
mobile:300},
{id:4
name:"Test"
mobile:400},
{id:5
name:"Temp"
mobile:500}]
What i need to do is, I have to compare records in an json array based on "name" key.
While comparing, if record1.name = record2.name then i have to remove entire record1 and append "mobile" value of record1 with record2 , this way.
This is the final output expected.
[{id:1
name:"Test"
mobile:100,200,400},
{id:2
name:"Temp"
mobile:300,500}]
I tried removing this way. But not able to append the "mobile" key values with each other.
var removeItem = name;
alert('Array before removing the element = ' + simple);
simple = jQuery.grep(simple,
function(value) { return value != removeItem; });
alert('Array before removing the element = ' + simple);
Can some one help me in this?
Thanks
Edit
======
I tried Answer#1=given by Ismail Kuruca given below,
Its working fine with the existing keys I.E, If added new keys with the below input,
var input =
[{
id:1,
name:"Test",
ssn:1,
mobile:100,
address:"A"
},
{
id:2,
name:"Test1",
ssn:2,
mobile:200,
address:"B"
},
{
id:3,
name:"Temp",
ssn:3,
mobile:300,
address:"C"
},
{
id:4,
name:"Test2",
ssn:4,
mobile:400,
address:"D"
},
{
id:5,
name:"Temp1",
ssn:5,
mobile:500,
address:"E"
}];
Its is giving same value of "name" to all the newly added keys , as below,
here "ssn" should be equal to 1, but it is returning "name" value : "test"
[{"id":1,"name":"Test","ssn":"Test","mobile":"100"},{"id":2,"name":"Test1","ssn":"Test1","mobile":"200"},{"id":3,"name":"Temp","ssn":"Temp","mobile":"300"},{"id":4,"name":"Test2","ssn":"Test2","mobile":"400"},{"id":5,"name":"Temp1","ssn":"Temp1","mobile":"500"}]
I tried this way,
//This part transforms your input to a map for each "name" attribute
//Each key has a value of array of "mobile"
var intermediateObject = {};
for(var i = 0; i < input.length; i++) {
if(typeof intermediateObject[input[i].name] == 'undefined') {
intermediateObject[input[i].name] = [];
}
else if(typeof intermediateObject[input[i].ssn] == 'undefined') {
intermediateObject[input[i].ssn] = [];
}
intermediateObject[input[i].name].push(input[i].mobile);
intermediateObject[input[i].ssn].push(input[i].mobile);
}
//Here the intermediate transformation is re-adjusted to look like your
//intended output format
var outputObject = [];
var index = 1;
for(elem in intermediateObject ) {
outputObject.push({
id: index++,
name: elem,
ssn : elem,
mobile: intermediateObject[elem].join(",")
});
}
console.log(JSON.stringify(outputObject));
but it is not working.. Can some help me in this..
Output should be,
[{
id:1,
name:"Test",
ssn:1,
mobile:100,
address:"A"
},
{
id:2,
name:"Test1",
ssn:2,
mobile:200,
address:"B"
},
{
id:3,
name:"Temp",
ssn:3,
mobile:300,
address:"C"
},
{
id:4,
name:"Test2",
ssn:4,
mobile:400,
address:"D"
},
{
id:5,
name:"Temp1",
ssn:5,
mobile:500,
address:"E"
}];
Could you please help?
Here is a very crude example of transforming your input to desired output.
var input =
[{
id:1,
name:"Test",
ssn:1,
mobile:100,
address:"A"
},
{
id:2,
name:"Test",
ssn:1,
mobile:200,
address:"A"
},
{
id:3,
name:"Temp",
ssn:3,
mobile:300,
address:"C"
},
{
id:4,
name:"Test2",
ssn:4,
mobile:400,
address:"D"
},
{
id:5,
name:"Temp1",
ssn:5,
mobile:500,
address:"E"
}];
//This part transforms your input to a map for each "name" attribute
//Each key has a value of array of "mobile"
var intermediateObject = {};
for(var i = 0; i < input.length; i++) {
if(typeof intermediateObject[input[i].name] == 'undefined') {
intermediateObject[input[i].name] = { ssn: null, address: null, content:[]};
}
intermediateObject[input[i].name].content.push(input[i].mobile);
intermediateObject[input[i].name].ssn = input[i].ssn;
intermediateObject[input[i].name].address= input[i].address;
}
//Here the intermediate transformation is re-adjusted to look like your
//intended output format
var outputObject = [];
var index = 1;
for(elem in intermediateObject ) {
outputObject.push({
id: index++,
name: elem,
ssn: intermediateObject[elem].ssn,
address: intermediateObject[elem].address,
mobile: intermediateObject[elem].content.join(",")
});
}
EDIT: Modified the answer according to edit:
This is the output object:
[{"id":1,"name":"Test","ssn":1,"address":"A","mobile":"100,200"},{"id":2,"name":"Temp","ssn":3,"address":"C","mobile":"300"},{"id":3,"name":"Test2","ssn":4,"address":"D","mobile":"400"},{"id":4,"name":"Temp1","ssn":5,"address":"E","mobile":"500"}]
I used a temporary object to figure out if a key is repeated or not. I then applied reduce to store objects with non-repeated keys and update the mobile array that they have with the mobile of the repeated element.
function final(arr) {
var aux = {}, index = 0;
return arr.reduce(function (memo, el) {
var key = el.name,
obj = aux[key];
if (!obj) {
aux[key] = {
id: index++,
name: key,
mobile: el.mobile
};
memo = memo.concat(aux[key]);
} else {
obj.mobile += "," + el.mobile;
}
return memo;
}, []);
}
console.log(final(arr));
You can check the result in this fiddle.
Hope it helps.
I need to make an extension to existing code, can't change it.
There's this array:
var availableTags = [
{ label: "Yoga classes", category: "EDUCATIONAL" },
{ label: "Cooking classes", category: "EDUCATIONAL" },
{ label: "Cheese tastings", category: "EDUCATIONAL" },
{ label: "Maker Workshops", category: "PRACTICAL" },
{ label: "Seminars", category: "PRACTICAL" },
//many more of these
];
Now I need to check if a text entered in an input box is included in one of the labels, e.g. if the user enters "Yoga classes" => OK, if "Yoga" => NOK, "sdsdf" => NOK, etc.
What is the best way to do this? I am not sure I can use Array.indexOf as I am not sure how to pass the Object to the function, I would try looping through the array (around 40 entries) and compare each object.
You need to loop over every item in availableTags and check whether that item's label is equal to some input. Try something like this:
var input = "Yoga classes";
var found = false;
for (var i = 0, j = availableTags.length; i < j; i++) {
var cur = availableTags[i];
if (cur.label === input) {
found = true;
break;
}
}
console.log(found);
DEMO: http://jsfiddle.net/k4cp4/4/
Where this can easily be put into a function, like:
var checkMatch = (function () {
var availableTags = [
{ label: "Yoga classes", category: "EDUCATIONAL" },
{ label: "Cooking classes", category: "EDUCATIONAL" },
{ label: "Cheese tastings", category: "EDUCATIONAL" },
{ label: "Maker Workshops", category: "PRACTICAL" },
{ label: "Seminars", category: "PRACTICAL" }
];
return function (input) {
var found = false;
for (var i = 0, j = availableTags.length; i < j; i++) {
var cur = availableTags[i];
if (cur.label === input) {
found = true;
break;
}
}
return found;
};
})();
DEMO: http://jsfiddle.net/k4cp4/5/
This checks for an exact match. So if you want a case insensitive match, you can use:
if (cur.label.toLowerCase() === input.toLowerCase()) {
DEMO: http://jsfiddle.net/k4cp4/6/
If you want to see if any of the labels contain the input, you can use indexOf like:
if (cur.label.indexOf(input) > -1) {
DEMO: http://jsfiddle.net/k4cp4/7/
You can use Array.some method:
Tests whether some element in the array passes the test implemented by the provided function.
Then your code would look something like:
var isFound = availableTags.some(function(el) {
return el.label === 'Yoga classes';
});
Note: some method needs to be shimmed.
var check = function(item) {
for(at in availableTags) {
if(item == availableTags[at].label) {
return true;
}
}
return false;
}
console.log(check("Yoga classes"));
I have the following object and what I would like achieve is to get the index of theme if the name has match with a variable.
for example: I'm making a loop in the views and if my task (something1) variable has matches with the name element than to return the index of object.
By the given example I should have as result 0,
var views = [
{
name: "something1",
type: something1,
columns: something1
},
{
name: "something2",
type: something2,
columns: something2
},
{
name: "something3",
type: something3,
columns: something3
}
];
var task = 'something1';
$.each(views, function(index, value) {
if (value.name = task) {
alert(index);
}
});
You dont really need jQuery for this:
See: http://jsfiddle.net/enNya/2/
var views = [
{
name: "something1",
type: "something1",
columns: "something1"
},
{
name: "something2",
type: "something2",
columns: "something2"
}
];
var task = 'something2';
// Set a var and maintain scope
var i;
// Loop each element of the array
for (i = 0; i < views.length; i++) {
// If the X = Y the stop looping
if (views[i].name == task) {
break;
}
}
// Check if it was not found
i = i == views.length ? false : i;
// Log the result
console.log(i);
It's just a matter of syntax, as lgt said don't forget toseparate elements within your object with commas. Aslo the correct 'equal' operator is '=='.
'value.name=task' would be always true. It means can I affect the content of 'task' into 'value.name'.
Here is your valid js.
Note that in this example you'll get 2 alertbox.. ;)
var views=[
{
name:"something1",
type:'something1',
columns:'something1'
},
{
name:"something1",
type:'something1',
columns:'something1'
},
{
name:"something2",
type:'something2',
columns:'something2',
},
];
var task='something1';
$.each(views, function(index, value) {
if (value.name==task){
alert(index);
}
});
replace something1 variable for 0 and value.name == task (double =)
var views=[{
name:"something1",
type:0,
columns:0
}, {
name:"something1",
type:0,
columns:0
}, {
name:"something2",
type:0,
columns:0
}];
var task='something1';
$.each(views, function(index, value) {
if (value.name==task){
return index;
}
});