Cannot form keyvalue pair in javascript in desired format - javascript

I have formed a keyvalue pair in JavaScript using the below code:
for(i=1;i<=results.totpage;i++)
{
pushToAry(i,i);
}
Assume results.totpage as 300.
The method pushToAry():
function pushToAry(name, val) {
//alert("In the array");
var obj = {};
obj[name] = val;
ary.push(obj);
}
where ary is defined as var ary = [];
Using the above format the result that comes out is like:
But I want to make it like [["key1", "value1"],["key2", "value2"],["key3", "value3"]] i.e. to replace the 2nd brackets with the 3rd brackets.
Please help.

Instead of pushing a object to ary, push a new array:
var ary = [];
function pushToAry(name, val) {
//alert("In the array");
var arr = [name, val];
ary.push(arr);
}

Related

How to remove partial duplicate values in jquery array

I have a single level array of key/value pairs, like this:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square']
I need a function to perform the following:
find all duplicate keys
replace the first occurrence of the key/value pair with the second occurrence
delete the second occurrence
In this case, it would produce the following result:
user_filters= ['color=blue', 'size=large', 'shape=square']
Something like...
function update_array(){
$.each(user_filters, function(i){
var key = this.split('=')[0];
if(key is second occurrence in user_filters)
{
var index = index of first occurrence of key
user_filters[index] = user_filters[i];
user_filters.splice(i,1);
}
});
}
What is the best way to do this? Thanks!
I would keep the data in an object and this way any duplicate will automatically overwrite the previous entry..
See this for example:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var object = {};
for (var i = 0; i < user_filters.length; i++) {
var currentItem = user_filters[i].split('=');
var key = currentItem[0];
var value = currentItem[1];
object[key] = value;
}
console.log(object);
You can use a hash object to get the key-value pairs without duplicates and then transform the hash object back into an array like this:
function removeDuplicates(arr) {
var hash = arr.reduce(function(h, e) {
var parts = e.split("=");
h[parts[0]] = parts[1];
return h;
}, {});
return Object.keys(hash).map(function(key) {
return key + "=" + hash[key];
});
}
var user_filters = ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
console.log(removeDuplicates(user_filters));
You could use a Map which does the unique/overriding automatically, and is able to get you an array back in case you need it
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var m = new Map(user_filters.map(v => v.split("=")));
console.log([...m.entries()].map(v => v.join("=")));
It would be better to iterate from back of array ,
thus for every unique key you need to keep a variable true or false (initially false).
so if true mean already occurred so deleted it else keep it and make its variable true .
It is much more better approach then your current . you don't have to keep last index and swapping then deleting.
You may convert to json and then back to the array format you want . IN the below code you get the result object in the format you want.
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
function toJson(obj){
var output = {};
$.each(obj, function(i){
var keyvalPair = this.split('=')
var key = keyvalPair[0];
output[key]= keyvalPair[1];
});
return output;
}
function toArray(obj){
var output = [];
$.each(obj, function(i){
output.push(i+"="+obj[i]);
});
return output;
}
var result = toArray(toJson(user_filters));
console.log(result);

Javascript: how to dynamically create nested objects INCLUDING ARRAYS using object names given by an array

Very similar to this question:
Javascript: how to dynamically create nested objects using object names given by an array
Instead of calling
assign(obj, keyPath, value)
example of usage of the previously answer:
var accountinfo = {}
assign(accountinfo, ["name", "addressinfo", "zipcode"], "90210");
That will output:
accountinfo = {name: "", addressinfo: {zipcode:"90210"}};
Now, I'd like to support arrays... in the above example, I'd like to support multiple addressinfo per account. I'd like to say:
assign(accountinfo, ["name", "addressinfo[1]", "zipcode"], "90210");
The result would be:
accountinfo = {name: "", addressinfo: [{},{zipcode:"90210"}]}
var regex = /\[([0-9]+)\]/ will show me the # inside the brackets, but I'm not sure how I'd have to iterate through each element in the array to make sure it exists (and create it if it doesn't).. and the difficult part, support this for each array element submitted as part of the function (I'd like to say :
assign(accountinfo, ["family", "name[3]", "addressinfo[1]", "zipcode"], "90210");
Edit:
Figured it out.
function assign(obj, keyPath, value) {
keyPath = keyPath.split(‘.’);
lastKeyIndex = keyPath.length - 1;
var re = /^(.+?)\[*(\d+)*\]*$/;
for (var i = 0; i < lastKeyIndex; i++) {
key = keyPath[i];
var ind;
var middle = re.exec(key);
key = middle[1];
ind = middle[2];
if (ind) {
if (!(obj[key]))
obj[key] = [];
if (!(obj[key][ind]))
obj[key][ind] = {};
}
if (!(key in obj))
obj[key] = {};
if (ind)
obj = obj[key][ind];
else
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}

Returning only certain properties from an array of objects in Javascript [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 8 years ago.
If I have an object such that
var object = function(key,text)
{
this.key = key;
this.text = text;
}
And create an array of these objects
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
is there a way that I can retrieve only one of the properties of all of the objects in the array? For example:
var keyArray = objArray["key"];
The above example doesn't return set keyArray to anything, but I was hoping it would be set to something like this:
keyArray = [
'key1',
'key2',
'key3']
Does anyone know of a way to do this without iterating through the objArray and manually copying each key property to the key array?
This is easily done with the Array.prototype.map() function:
var keyArray = objArray.map(function(item) { return item["key"]; });
If you are going to do this often, you could write a function that abstracts away the map:
function pluck(array, key) {
return array.map(function(item) { return item[key]; });
}
In fact, the Underscore library has a built-in function called pluck that does exactly that.
var object = function(key,text) {
this.key = key;
this.text = text;
}
var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');
var keys = objArray.map(function(o,i) {
return o.key;
});
console.log(keys); // ["key1", "key2", "key3"]
JS Bin Example
http://jsbin.com/vamey/1/edit
Note that older browsers may not support map but you can easily do this with a for loop:
var keys = [];
for (var i = 0; i < objArray.length; i++) {
keys.push(objArray[i].key);
}
JS Bin Example
http://jsbin.com/redis/1/edit
You would want to do something like this:
objArray.map(function (obj) { return obj.key; });
Here is a JSFiddle to demo: http://jsfiddle.net/Q7Cb3/
If you need older browser support, you can use your own method:
JSFiddle demo: http://jsfiddle.net/Q7Cb3/1/
function map (arr, func) {
var i = arr.length;
arr = arr.slice();
while (i--) arr[i] = func(arr[i]);
return arr;
}
Well something has to iterate through the elements of the array. You can use .map() to make it look nice:
var keys = objArray.map(function(o) { return o.key; });
You could make a function to generate a function to retrieve a particular key:
function plucker(prop) {
return function(o) {
return o[prop];
};
}
Then:
var keys = objArray.map(plucker("key"));
Really "objArray" is an array that have 3 objects inside, if you want list of keys, you can try this:
var keys = [];
for(a in objArray) {
keys.push(objArray[a].key);
}
You have in var keys, the three keys.
Hope that helps! :)

Javascript: Convert Array to Object

Which is the easiest way to convert this:
[{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}]
to this:
{src:"websrv1", dst:"websrv2", dstport:"80"}
in order to pass it to AJAX data?
I'm using VisualSearch and it returns an array of Facet model instances which i need to convert into an Object.
var a = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var b = a.reduce(
function(reduced,next){
Object.keys(next).forEach(function(key){reduced[key]=next[key];});
return reduced;
}
);
//b should be {src:"websrv1", dst:"websrv2", dstport:"80"}
think about the array.reduce function everytime you need to perform these kind of transformations.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
If you are using jquery, try this:
var array = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}]
var arrayObj = {};
for(var i in array) {
$.extend(arrayObj, array[i]);
}
Use .reduce().
var result = data.reduce(function(obj, item) {
for (var key in item)
obj[key] = item[key];
return obj;
}, {});
Don't use this! but just for fun
var a = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var f = a.reduce((c,d) => Object.assign(c,d), {})
The tiny drawback is that a is mutated with an infinite recursive object but, who cares? it works in one line!
My 2cents, very easy to read:
var myObj = {};
myArray.forEach(function(obj) {
var prop = Object.keys(obj)[0];
myObj[prop] = obj[prop];
})
Original answer using only the most basic features of JavaScript:
var input = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var output = {};
for (var i = 0; i < input.length; i++) {
for (var n in input[i]) {
output[n] = input[i][n];
}
}
console.log(output);
UPDATE: Using newer features of JavaScript, you can do this trivially with Object.assign and spread syntax (...):
var input = [{src:"websrv1"}, {dst:"websrv2"}, {dstport:"80"}];
var output = Object.assign({}, ...input);
console.log(output);
Also, Object.assign(...input) will return the same result, but will modify the first element of the input array. As long as you don't mind that side effect, I'd use this simpler version.

How to convert Object into array in jquery/javascript

I want to convert an object with specific properties into array of string containing properties values. For an instance take Object Employee with below properties with values
Employee.Name='XYZ'
Employee.ID=123
Employee.Address='ABC'
I want this all to be in array as
var arr=['XYZ',123,'ABC']
How to iterate over the properties. Is this possible? Please assist here.
Use $.map()
var arr = $.map(Employee, function(value, key){
return value
})
Demo: Fiddle
Note: The order of loop is not dependable, so the order of values in the array may not be always same
Another way to handle it is to use a fixed array of keys so that the output array will have a predefined sequence
var keys = ['Name', 'ID', 'Address'];
var Employee = {};
Employee.Name = 'XYZ'
Employee.ID = 123
Employee.Address = 'ABC'
var arr = $.map(keys, function (key, idx) {
return Employee[key]
})
console.log(arr)
Demo: Fiddle
Loop through the object like this
var arr = [];
for (var key in Employee) {
arr.push(Employee[key]);
}
Note: Order is not defined in this case
You can loop through each property and add it's value to the array:
var arr = [];
for (var prop in Employee) {
if (Employee.hasOwnProperty(prop)) {
arr.push(Employee[prop]);
}
}
Example - http://jsfiddle.net/infernalbadger/2PHpZ/
Or using jQuery:
var arr = $.map(Employee, function(propValue) {
return propValue;
});
Example - http://jsfiddle.net/infernalbadger/2PHpZ/1/
var myArray=[];
for (var key in Employee) {
if (Employee.hasOwnProperty(key)) {
myArray.push(Employee[key]));
}
}
var Employee = {};
Employee.Name='XYZ';
Employee.ID=123;
Employee.Address='ABC';
var empArray =[];
$.each(Employee,function(item){
empArray.push(item);
});
console.log(empArray);
fiddle
JavaScript since 1.7. Reference to JavaScript language advanced Tips & Tricks.
var arr = [Employee.Name,Employee.ID,Employee.Address];

Categories

Resources