I have the following objects:
var empAry= [{"empid":"101","name":"David"},{"empid":"102","name":"Sam"}..];//2000 records
var empAry2= [{"empid":"101","name":"David"},{"empid":"105","name":"Kevin"},{"empid":"109","name":"Robert"},{"empid":"110","name":"Rob"}..];//30000 records
I need to add new element to the empAry object and populate new element value based on the availability of that particular record in empAry2.
Expected Output:-
empAry= [{"empid":"101","name":"David", **"FounInempAry2":"Yes"**},{"empid":"102","name":"Sam", **"FounInempAry2":"No"}**..];//2000 records
If we can do it by jquery that would be good. Please help me.
It's hard to make sense of what FounInempAry2 is since the object structures are identical in both samples. I will assume that other properties exist and will use jQuery $.extend() to "merge" the properties.
First it is likely most efficient to loop through the big array once and create an object using the empid as keys.
var tmp = {};
$.each( empAry2, function(_, item){
tmp[ item.empid ] = item;
});
This creates an object like:
{
"101" : {"empid":"101","name":"David"},
"102" : {"empid":"102","name":"Sam"}
}
Now loop through first array and extend with whatever is in matching object in the tmp object
$.each( empAry, function(_, item){
$.extend( item, tmp[ item.empid ]);
});
Reference: $.extend() Docs
Try this:
var entry = {"empid":"<some id>","name":"<some name>"}
var filter = empAry2.filter(function(o){
return o.empid==entry.empid;
});
entry.FounInempAry2=(filter && filter.length>0)?"Yes":"No";
empAry2.push(entry);
Or
var entry = {"empid":"<some id>","name":"<some name>","FounInempAry2":"No"}
for(var i=0,length=empAry2.length;i<length;i++){
if(empAry2[i].empid==entry.empid){
entry.FounInempAry2="Yes";
break;
}
}
empAry2.push(entry);
Related
This is my array:
var country = ["US(+1)","IND(+91)"];
And i want to convert my array in this below format:
country = [
{
title: "US(+1)",
},
{
title: "IND(+91)",
}
]
word title should be same for each array value.
with this code am trying to get my expected result as above
var obj = country.reduce(function(o, val) { o['title'][] = val; return o; }, {});
But my output is comes like this as below: only last index is taking place
{"title":"IND(+91)"} this is wrong output which i dont want
You may be able to do it with reduce but it's much easier to use map:
var country = ["US(+1)","IND(+91)"];
var obj = country.map(function(c){return {title:c}});
console.log("country:", country);
console.log("obj:", obj);
map is for when you want to turn an array of things into another array of things, and reduce is when you want to turn an array of things into just a single thing.
var country = ["US(+1)","IND(+91)"];
I would use a more descriptive word since it is a list of countries.
var countries = ["US(+1)","IND(+91)"];
But to answer your question, to manipulate an array into a new array, I like to use the array.map method:
var objects = countries.map(function(country){ return { title: country } });
Here is the documentation for map:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?v=control
I need one help. I need to insert one new value into existing array by matching the key value using Javascript.I am explaining the scenario below.
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
]
The above is my existing array.I need to match with the below another array.
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
Here i need to match the array arr with an array galArr if image name will same this checked:true will add in the rective row of existing array galArr. Suppose arr[0].image==galArr[0].image then checked:true will add in that respective row of existing array. Please help me.
This should be sufficient.
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
];
// start looping over `arr`
arr.forEach(function(o, i){
// now loop over `galArr` to find match
galArr.forEach(function(gO, i){
// when there is a match
if(o.image == gO.image){
console.log(gO);
// add checked property to this object
gO['checked'] = true;
}
});
});
// Output
console.log(galArr);
First of all check condition and if the condition match then create a new temp json and replace it with old json
arr.forEach(function(d){
galArr.forEach(function(e){
if(e.image==d.image){
temp = {};
temp.image = e.image;
temp.comment = e.comment;
temp.checked = e.comment;
temp.action = e.action;
e = temp;
}
});
});
I would create an image index, where its indexes would be the whole image file names and later I would use that image index to quickly check and add checked property to galArr array:
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var imageIndex = galArr.map(function(item) {
return item.image;
});
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
arr.forEach(function(item) {
item.checked = imageIndex.indexOf(item.image) > -1;
});
If your users will use your JavaScript code within a modern Web browser, I would use the new Set collection:
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var imageIndex = galArr.reduce(function(result, item) {
result.add(item.image);
return result;
}, new Set());
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
arr.forEach(function(item) {
item.checked = imageIndex.has(item.image);
});
I've asked a question to assist everyone in understanding how valueable are sets: Is Set a hashed collection in JavaScript?
Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.
I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)
I have the following code to get the order of elements. But instead of getting an array in the order of the elements, it's alphabetical.
function gatherTreeIds( $parent ){
var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
GatheredIds[ this.title ] = 'someValue';
});
return GatheredIds;
}
<div id="Wrap">
<div class="nt_row" title="AAA"></div>
<div class="nt_row" title="CCC"></div>
<div class="nt_row" title="BBB"></div>
</div>
Here is my jsFiddle example (check console for result). It gives me ['AAA','BBB','CCC'] instead of the desired ['AAA','CCC','BBB'].
Important! This has to get recursive. It is not at this moment to simplify the problem.
You're confusing the two concepts of arrays and hashes. Arrays have order, while hashes have named keys, you can't have both in a data single structure.
With an array you would use:
var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
GatheredIds.push('someValue');
});
return GatheredIds;
If you want to record the item title, you can use an array of hashes:
var GatheredIds = [];
$parent.children('div.nt_row').each(function(){
GatheredIds.push({value: 'someValue', title: this.title);
});
return GatheredIds;
This happens because you store titles as object properties. In your example GatheredIds is not array, this is an object.
Objects in JavaScript do not have order (opposite to PHP's map-arrays). If you need to follow the order, you should use arrays instead.
One possible solution:
function gatherTreeIds( $parent ){
return $parent.children('div.nt_row').map(function() {
return {
title: this.title,
value: 'someValue'
};
}).get();
}
DEMO: http://jsfiddle.net/FmyBb/4/