How to Convert an Array into Object of key value pair - javascript

I need to convert an array into object with key values.For Example
var Array = [17.3850, 78.4867]
I need to convert into Object in this manner
var Object = {"lat":17.3850, "lng":78.4867}

Using Array.prototype.map() make an iteration over the array, create an array of Object and finally convert that to an object using Object.assign().
var key = ['lat', 'lng'];
var array = [17.3850, 78.4867]
var obj = Object.assign({}, ...key.map((e, i) => ({[e]: array[i]})))
console.log(obj)

You could map an array with arrays of key/value pairs and create an object with Object.fromEntries.
var array = [17.3850, 78.4867],
keys = ['lat', 'lng'],
object = Object.fromEntries(array.map((v, i) => [keys[i], v]));
console.log(object);

you can use the constructor in JavaScript.
class Location {
constructor(lat, lng) {
this.lat = lat,
this.lng = lng
}
}
var myArray = [17.3850, 78.4867];
var myLocation = new Location(myArray[0], myArray[1]);
myLocation.lat;
myLocation.lng;
Instead of myArray[0] & myArray[1] you can use loop to make it dynamic.

Related

How to collect / make new array by existing arrays label wise?

How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console

Push Duplicate key data on key array in javascript

I have this data structure. I have used the underscorejs but could not find way to that like the below structure
var data = [{"5+":2},{"3-5":0},{"1-3":1},{"0.5":0},{"<30":0},{"5+":1},{"3-5":1},{"1-3":0},{"0.5":0},{"<30":0},{"5+":3},{"3-5":0},{"1-3":3},{"0.5":0},{"<30":0}];
var groupArr = [];
##loop through the data##
data.forEach(function(item){
##find the keys ##
var keys = Object.keys(item);
var obj = {};
obj[keys] = [];
##push the data to object keys array##
obj[keys].push(item[keys])
groupArr.push(obj)
})
By using this data structure I want something like this structure
[{"5+":[2,1,3]},{"3-5":[0,1,0]},{"1-3":[1,0,,3]},{"0.5":[0,0,0]},{"<30":[0,0,0]}]
As I have tried everything but could not find the solution any help would be highly appreciated.
The first part converts the list of objects to a single object, where the keys are each of the unique keys from the list of objects and the values for each key are joined as an array:
{
"5+": [2,1,3],
"3-5": [0,1,0]
...
}
Since this is not the format you wanted, the second part converts this object into a list of objects by looping over each key and creating a new object from it.
var data = [{"5+":2},{"3-5":0},{"1-3":1},{"0.5":0},{"<30":0},{"5+":1},{"3-5":1},{"1-3":0},{"0.5":0},{"<30":0},{"5+":3},{"3-5":0},{"1-3":3},{"0.5":0},{"<30":0}];
// create object with all the values joined together in lists.
var map = data
.reduce(function (map, obj) {
var key = Object.keys(obj)[0];
// checks if the key allready exits in the new object.
// If it does we push a new value into the array,
// otherwise we create a new property with a list with one value.
map[key] ?
map[key].push(obj[key]):
map[key] = [obj[key]];
return map;
}, {});
// convert above result to a list with objects.
var newFormat = Object.keys(map)
.map(function (key) {
var obj = {};
obj[key] = map[key];
return obj;
})
console.log(newFormat)

Length property not updating on object arrays

Two problems consider the following object:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
Why does my cars array have length of 0? Do i have to update the length property manually?
Why is my stringified object empty when it has parameters in it i'm assuming it is tied into the length property?
Fiddle:https://jsfiddle.net/wcd7f8Lz/
car is initialized as an array, but used as an Object. and an object does not have length attribute...
To get the length of an object, you can do ̀̀̀̀Object.keys(obj).length (get the keys list, and because it is an array, it have a length).
But the problem is also that you initialize cars as an array, but use it as Object...
see docs here:
http://www.w3schools.com/js/js_arrays.asp
http://www.w3schools.com/js/js_objects.asp
The solution is to initialize it as Object:
//new obj
var obj = {};
obj['cars'] = {}; //And other object
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
But if you want instead a simple array:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars'][1] = "toyota";
obj['cars'][0] = "mazda";
console.log(obj);
console.log(JSON.stringify(obj));
The syntax is ̀array[identifier] = value;
(and not ̀̀̀̀̀array[value] = identifier)
I've updated the fiddle.
obj.cars.length is 0, because you don't push new items in array, but change it properties:
var obj = {};
obj.cars = []; // obj.cars is empty array
obj.cars.toyota = 1; // obj.cars is empty array with a new property toyota
obj.cars.push('mazda'); // obj.cars is array with a new property toyota and one element mazda
console.log(obj.cars instanceof Array,
obj.cars.length,
Object.keys(obj.cars)); // output: true 1 ["toyota"]
Why you don't use it in this way?
var cars = [];
cars.push({name:'toyota', value:1});
cars.push({name:'mazda', value:0})
That's because you aren't using an array (despite declaring it with an array literal), you're using it as an object.
Arrays are just a special case of object, meaning they can have individual properties. These properties don't exist "in" the array but instead are properties "of" the array.
var arr = [1, 2, 3];
arr.thing = 'a';
console.log(arr.length); // 3
To add elements to an array, you should use push:
var arr = []; // length: 0
arr.push(1); // length: 1
If you want to be able to access an object both by name and index then you can combine push with custom properties.
var arr = [];
arr.push(0);
arr.mazda = 0;

Manipulate Json String Jquery

Supposed that I have this JSON STRING that is stored in a vairable:
{"name":"Joene Floresca"},{"name":"Argel "}
How can I make it
["Joene", "Argel"]
You mention you have a string. Use JSON.parse for that. Also, make sure it is an array. Afterwards, you can manually iterate through each object in the array and push the value
var str = '[{"name": "Joene Floresca"},{ "name": "Argel "}]';
var objA = JSON.parse(str);
var values = [];
for (var i = 0; i < objA.length; i++) {
for (var key in objA[i]) {
values.push(objA[i][key]);
}
}
console.log(values);
Assuming your JSON is an array, you can use map:
// Your JSON string variable
var jsonString = '[{"name":"Joene Floresca"},{"name":"Argel "}]';
// Parse the JSON to a JS Object
var jsObject = $.parseJSON(jsonString);
// Use map to iterate the array
var arr = $.map(jsObject, function(element) {
// Return the name element from each object
return element.name;
});
console.log(arr); // Prints ["Joene Floresca", "Argel "]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can iterate over objects inside array and store the names in a second array.
var data = JSON.parse('[{"name":"Joene Floresca"},{"name":"Argel "}]');
var names = [];
data.forEach(function(model) {
names.push(model.name);
});
// names now contains ["Joene Floresca", "Argel"]
alert(names);

Map in map storing

how can I store map in map in javascript?
var data = {};
data['key'] = {'val1', 'val2'};
And I get an error about wrong id.
You either need an array...
var data = {};
data['key'] = ['val1', 'val2']; // store an Array at data.key
data.key[0]; // 'val1'
...or keys for your values in the object...
var data = {};
data['key'] = {key1:'val1', key2:'val2'}; // store an Object at data.key
data.key.key1; // 'val1'
If you want just an array (a list) in the data map, what patrick dw has is fine.
If you want a map in your data map, you need the following:
var data = {};
data['key'] = {'val1': 'val2'}; // using a colon instead of a comma to create key-value pairing
You can also simplify this using JavaScript object notation:
var data = {};
data.key = {val1: 'val2'};

Categories

Resources