I'm trying to make a javascript key-value array with the key as the name of the person and the value as a numerical one indicating their compatibility (1 lowest, 10 highest). Something like this :
var array = [ {name: "Sean", value: 7},
{name: "Sarah", value: 8},
{name: "Chloe", value: 5} ];
However I want to create the array somewhat dynamically, where two separate arrays- one of names and one of numbers - would make up the key-values. How would I go about doing this?
simply by specifying the names as key and the corresponding values as value
var ar = {};
var name = 'xyz';
var value = 1;
ar[name] = value;
Try this syntax:
var array = {"Sean":7,"Sarah":8,"Chloe":5};
And if you want to add the items one by one:
var array = {};
array["Sean"] = 7;
array["Sarah"] = 8;
array["Chloe"] = 5;
Related
I have an array:
var array1 = [{ make: "John Deere", model: "4030", time:"-KzbzyNy-nh1E3wQY7uz", uid:0, year:"1952" }]
I want to grab the "time" value and set it to the "uid" value. So, it would become:
var array1 = [{ make: "John Deere", model: "4030", time:"-KzbzyNy-nh1E3wQY7uz", uid:"-KzbzyNy-nh1E3wQY7uz", year:"1952" }]
It's totally fine if "-KzbzyNy-nh1E3wQY7uz" is repeated because it's set to two different keys.
How would I go about this? I'm new to javascript., so sorry if this is too basic of a question.
This solution will work for an array of any length. Some of the other solutions will only work if the array is of length 1 and the object you want to modify will always be in the array.
This solution will work for an array (of similar objects) of any length.
for(var i = 0; i < array1.length; i++) {
var current = array1[i];
current.uid = current.time;
}
try this one
var array1 = [{
make: "John Deere",
model: "4030",
time: "-KzbzyNy-nh1E3wQY7uz",
uid: 0,
year: "1952"
}];
//set it manually using key of array
array1[0]['uid'] = array1[0]['time'];
console.log(array1);
Loop over array and make a simple assignment for each object by passing the value of time to the property uid
var array1 = [{
make: "John Deere",
model: "4030",
time: "-KzbzyNy-nh1E3wQY7uz",
uid: 0,
year: "1952"
}];
// o is current array element which is an object
array1.forEach(o => o.uid = o.time);
console.log(array1);
I wish I could choose more answers than just one. All of these work, I didn't know it was as easy as assigning one value to the next. Here's my final code:
const array2 = [];
array1[0].uid = array1[0].time;
const len = array1.length;
for (let i = 0; i < len4; i++) {
array2.push(array1);
}
console.log(array2);
I probably don't need array2 in there at all, but just added that other step.
I'm new in Javascript. I have an object and I need to compare it with a variable and then if conditions are met I do something. How can i get access to the fields that I need?
I took this variable: $scope.acceptedProjects['hash'][key]['title']
Here is my code:
$scope.overlappingDates = overlappingDates;
$scope.acceptedProjects = invitationService.acceptedProjects;
for(var value in $scope.overlappingDates) {
for(var key in $scope.acceptedProjects['hash']) {
console.log($scope.overlappingDates);
console.log($scope.acceptedProjects['hash'][key]['title']);
}
}
return;
If I try $scope.overlappingDates[value], it returns
And I just need to slice or do something to convert this massive name to var.
Not sure if I've got what do you want to achieve. But look at this abstract example step by step and understand what is going on here. I hope this will help you to get more familiar with accessing object properties and array items:
var data = {
prop1: [
{meaning_property: 1},
{meaning_property: 2},
{meaning_property: 3}
],
prop2: [
{meaning_property: 4},
{meaning_property: 5},
{meaning_property: 6}
]
};
var found_field_name = null;
var found_item_index = -1;
var looking_for_value = 5;
// loop through data's fields
for (var prop in data) {
// access the value of object's field prop1, prop2 etc...
var arr = data[prop];
// loop through array
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
// item property value meets the condition?
if (item.meaning_property === looking_for_value) {
// remember field name for array
found_field_name = prop;
// remember item index in array
found_item_index = i;
// break the cycle here, we've found what we need
break;
}
/**
* item.meaning_property you can also access in different ways
* arr[i].meaning_property
* data[prop][i].meaning_property
* data["prop1"][0].meaning_property
* data.prop1[0].meaning_property
*/
}
}
// if we found something during previos loop
if (found_field_name !== null) {
// access the corresponding array
var arr = data[found_field_name];
// access the corresponding item
var item = arr[found_item_index];
console.log("Item found", found_field_name, found_item_index, arr, item);
}
else {
console.log("No items met the criteria");
}
Try to play with this code, I'm sure, you'll find the way to solve your task finally.
From the browser output I see, that overlap1 is array that contains objects inside. Thats how to get object values
for (var i = 0; i < overlap1.length; i++;){ //iterate over all objects inside array
var el = overlap1[i];
//get variables of object
var projectDateId = el.project_date_id// or el["project_date_id"];
var projectsProjectId = el.projects_project_id// or el["projects_project_id"];
//do something with this variables
}
I have an array that contains objects, like this:
[{
"first" : 1
},
{
"second" : 2
},
{
"third" : 3
}]
I want to turn this into two arrays, with indexes matching based on these values, such as:
["first","second","third"]
[1,2,3]
I can iterate through this and get the object keys and values, but I feel there's gotta be a slick way in lodash to do this, that I don't know of. Any suggestions? Thank you!
It seems like you just need to map over the object and call keys() and values()
You will get the first array like:
var items = [{a: "1"},{b: "blah",c: "what"},{d: "3"}]
keys = _(items).map(_.keys).flatten().value()
returns ["a","b","c","d"]
And the second array like:
values = _(items).map(_.values).flatten().value()
returns ["1","blah","what","3"]
For a non-lodash solution:
var arr = [{"first" : 1},{"second" : 2},{"third" : 3}];
var keys = arr.map(function(el){return Object.keys(el)[0];});
var vals = arr.map(function(el){return el[Object.keys(el)[0]];});
For the opposite problem (multiple arrays into one array of objects), see Merge two arrays into an array of objects with property values
Assuming that your object shape is always {"label": value}, then you can use this vanilla JavaScript:
var data = [{"first" : 1},{"second" : 2},{"third" : 3}];
var labels = data.map(function(entry) {
return Object.keys(entry)[0];
});
var values = data.map(function(entry) {
return entry[Object.keys(entry)[0]];
});
Your data structure seems sub-optimal based on your comments. I would recommend an alternate structure:
var data = [
{'label': 'first', 'value': 1},
{'label': 'second', 'value': 2},
{'label': 'third', 'value': 3}
]
Which is then trivial to pick out the labels and values into separate pieces in normal JavaScript:
var labels = data.map(function(entry) {
return entry.label;
});
var values = data.map(function(entry) {
return entry.value;
});
Or if you really want to use lodash:
var labels = _.pluck(data, 'label');
var values = _.pluck(data, 'value');
Hopefully you can see that this revised structure makes the JavaScript much simpler whether you use lodash or not.
I have two arrays of objects. arrayOne contain items type of myObject1:
var myObject1 = {
Id: 1, //key
params: { weight: 52, price: 100 },
name: "",
role: ""
};
arrayTwo contained items type of myObject2:
var myObject2 = {
Id: 1, //key
name: "real name",
role: "real role"
};
I want to copy all names and roles from arrayTwo to arrayOne.
id is the key, both arrays contains myObjects with that is mached by 'id`.
If the two arrays are guaranteed to be congruent, then with the use of jQuery.extend(), the code is trivial :
$.each(arrayOne, function(i, obj) {
$.extend(obj, arrayTwo[i]);
});
A solution that runs in linear time.
var arrayOne; // Array containing objects of type myObject1
var arrayTwo; // Array containing objects of type myObject2
var tempObj = {};
// Transform arrayOne to help achieve a better performing code
arrayOne.forEach(function(obj){
tempObj[obj.id] = obj;
});
// Runs on linear time O(arrayTwo.length)
arrayTwo.forEach(function(obj){
// Note, since I'm not adding any thing to the arrayTwo
// I can modify it in this scope
var match = tempObj[obj.id];
if(match){
// If a match is found
obj.name = match.name;
obj.role = match.role;
}
});
My question is related to this question. You will have to first read it.
var ids = "1*2*3";
var Name ="John*Brain*Andy";
var Code ="A12*B22*B22";
Now that I have an array of javascript objects. I want to group my objects based on CODE. So there can be duplicate codes in that code string.
As per the above changed strings, I have same code for Brain and Andy. So, now I want two arrays. In one there will be only one object containing details of only John and in the other object there will be two objects containing details of Brain and Andy.
Just for example I've taken 3 items. In actual there can be many and also there can be many set of distinct codes.
UPDATE
I needed the structure like the one built in groupMap object by the #Pointy. But I will use #patrick's code to achieve that structure. Many thanks to both of them.
It is a little hard to tell the exact resulting structure that you want.
This code:
// Split values into arrays
Code = Code.split('*');
Name = Name.split('*');
ids = ids.split('*');
// cache the length of one and create the result object
var length = Code.length;
var result = {};
// Iterate over each array item
// If we come across a new code,
// add it to result with an empty array
for(var i = 0; i < length; i++) {
if(Code[i] in result == false) {
result[ Code[i] ] = [];
}
// Push a new object into the Code at "i" with the Name and ID at "i"
result[ Code[i] ].push({ name:Name[i], id:ids[i] });
}
Will produce this structure:
// Resulting object
{
// A12 has array with one object
A12: [ {id: "1", name: "John"} ],
// B22 has array with two objects
B22: [ {id: "2", name: "Brain"},
{id: "3", name: "Andy"}
]
}
Split the strings on "*" so that you have 3 arrays.
Build objects from like-indexed elements of each array.
While building those objects, collect a second object that contains arrays for each "Code" value.
Code:
function toGroups(ids, names, codes) {
ids = ids.split('*');
names = names.split('*');
codes = codes.split('*');
if (ids.length !== names.length || ids.length !== codes.length)
throw "Invalid strings";
var objects = [], groupMap = {};
for (var i = 0; i < ids.length; ++i) {
var o = { id: ids[i], name: names[i], code: code[i] };
objects.push(o);
if (groupMap[o.code]) {
groupMap[o.code].push(o);
else
groupMap[o.code] = [o];
}
return { objects: objects, groupMap: groupMap };
}
The "two arrays" you say you want will be in the "groupMap" property of the object returned by that function.