If I have array of objects like this
[
{
"name" : "some name",
"more data" : "data",
...
},
{
"name" : "another name",
"more data" : "data",
...
},
...
]
And I want to copy the array, but only the name element in the object so that I have this:
[
{
"name" : "some name",
},
{
"name" : "another name",
},
...
]
Is there a short hand way to do this without writing a loop?
No, you have to do this with a loop, but in can still be short:
for(var i = 0; i < arr.length; i++)
arr[i] = {name: arr[i].name};
If you use any sort of framework or library all it will do is hide the loop from you. It will still loop through everything.
Example
No, there is no way of doing this without a loop. Can I suggest you do this with a bit of prototyping magic. (Note, this can be done with some map or forEach magic which just hides away the fact that you're looping. I'll leave this with the loop to illustrate the idea)
Array.prototype.clone = function(predicate)
{
var newArray = [];
for(var i = 0;i <this.length; i++){
var newElement = {};
for(x in this[i]){
if(predicate(x)){
newElement[x] = this[i][x];
}
}
newArray.push(newElement);
}
return newArray;
}
This allows you to clone an array, passing in a function that decides which property to keep from each element in the array. So given an array like:
var arr = [
{
"name" : "some name",
"more data" : "data"
},
{
"name" : "another name",
"more data" : "data"
}
];
You can do
var newArray = arr.clone(function(x){ return x == "name";});
Which will return you an array with the same number of objects, but each object will just have the name element.
Live example: http://jsfiddle.net/8BGmG/
Related
I need to get a list of all the key names in the following JSON object:
var myJSON = [
{
"Employees_Name": "Bill Sanders",
"Work_plan_during_my_absence": "Work from home",
"Assigned To-Manager Approval": [
"mymanager#gmail.com"
],
"AbsenceVacation_Summary": [
{
"Computed_Leave_Days": 2,
"From_Date": "2018-08-20",
"To_Date": "2018-08-21",
"Id": "Shccbcc230_a30f_11e8_9afa_25436d674c51"
}
],
"Leave_Type": "Work from Home",
"Reporting_Manager": "My Manager",
"Total_Days": 2,
}
]
When I use the Object.keys method, it retrieves only the top level key names:
var keys_arr = Object.keys(myJSON[0]);
console.log(keys_arr);
The result is an array:
"[ 'Employees_Name', 'Work_plan_during_my_absence', 'Assigned To-Manager
Approval', 'AbsenceVacation_Summary', 'Leave_Type', 'Reporting_Manager',
'Total_Days']"
The key names that are missing are the ones inside of 'AbsenceVacation_Summary'.
I think what I need to do is loop through the array of names returned and see if the value is an object or an array...but I don't know how to do this. Please advise.
You're right you need to walk your object structure recursively to discover nested objects and collects their keys:
function collectKeys(inputObject, outputKeys) {
if (Array.isArray(inputObject)) {
for(let i = 0; i < inputObject.length; i++) {
collectKeys(inputObject[i], outputKeys);
}
} else if (typeof inputObject === 'object') {
Object.keys(inputObject).forEach(function(key) {
outputKeys.push(key);
collectKeys(outputKeys[key], outputKeys);
});
}
}
var collectedKeys = [];
collectKeys(myJSON, collectedKeys);
Working fiddle here
Result will show in console
References
javascript typeof
javascript Array.isArray
javascript Array.forEach
I have this array :
var hemicycle = {
Group1 : [{
GroupName : "Les bests",
Member1 : [{
Name : "Loris Plasson",
Seat : 4,
Vignette : "PhotoURL"
}],
Member2 : [{
Name : "Anne-Sophie",
Seat : 3,
Vignette : "PhotoURL"
}]
}]
I want to push the object Member1 or Member2 on another object depending of the Seat value.
To do that I think I need to "search" for the Seat value with a for loop and retrieve the object, but all the examples I found on StackOverflow were with simple arrays like this :
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
With those simple arrays they are able to use something like a for loop with array[i].
But in my case I really don't know what to do...
UPDATE : What I want : The Member object which include the corresponding Seat value searched. Then I push the Member object to another object.
Thanks for any help.
The data structure that you use doesn't reflect what you are trying to convey, and in addition is very heard to traverse.
I suggest creating an array of groups. Each group is an object, that has the members property, which is an array of member objects:
[{
"GroupName": "Les bests",
"members": [{
"Name": "Loris Plasson",
"Seat": 4,
"Vignette": "PhotoURL"
},
{
"Name": "Anne-Sophie",
"Seat": 3,
"Vignette": "PhotoURL"
}
]
}]
Using this structure, you find a member using 2 for loops - one to iterate the groups, and the other to iterate the members of each group. Once a member is found, the function returns the member's object immediately. If not undefined is returned:
var groups = [{"GroupName":"Les bests","members":[{"Name":"Loris Plasson","Seat":4,"Vignette":"PhotoURL"},{"Name":"Anne-Sophie","Seat":3,"Vignette":"PhotoURL"}]}];
var seatNum = 4;
function findMember(seatNum) {
var members;
for(var i = 0; i < groups.length; i++) {
members = groups[i].members;
for(var j = 0; j < members.length; j++) {
if(members[j].Seat = seatNum) {
return members[j];
}
}
}
}
var member = findMember(seatNum);
console.log(member);
I have an array
[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]
is it possible to become key value pair?
{
"flight1" : "123",
"flight2" : "456"
}
You can use reduce() and return object as result.
var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}]
var result = arr.reduce(function(r, e) {
r[e.field] = e.value;
return r;
}, {});
console.log(result)
The new Map() constructor can do this for you:
var data = [
{"field": "flight1", "value": "123"},
{"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));
If you're not familiar with Map objects, they work almost exactly the same as plain objects, except they are a little easier to iterate over, and have a .size property.
But if you prefer to have a plain object, you can get one this way:
var result = Object.fromEntries(data.map(obj => [obj.field, obj.value]));
You could map the key value pair and assign it to an object.
var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
result = Object.assign(...data.map(a => ({ [a.field]: a.value })));
console.log(result);
you could use a standard for loop:-
var data = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}];
var obj = {};
for (var i = 0; i < data.length; i++)
obj[data[i].field] = data[i].value;
console.log(obj);
This might help someone another day. I tried all the examples above, but each time the console was giving me something like this:
{
flight1: "123",
flight2: "456"
}
My problem was that I was converting a serialized array way to soon which resulted in lots of tiny problems. Below was the code that didn't work:
var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);
Note that flight1 and flight2 lost their double quotes. Below was my solution:
var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);
NB: This was a code for submitting user information to a database (neDB) using the electron framework
Below is my json structure. On success of collection.fetch() i'm looping through the structure.
Currently i use
this.collection.each(function(model) { .. }
How do i obtain key name like plants, animals and instead loop using the names.
JSON
var jsonObj = { // 0 - recommended , 1 - New
"plants" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
],
"animals" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
]
};
Snapshot of collection
This would work, but you'd use a normal for loop, not "each":
for(i in jsonObj){
alert(i);
}
here is a fjsfiddle: http://jsfiddle.net/r5nwP/
Is that what you're after?
You can use the underscore keys to get a list of names:
var thenames =_.keys(yourobject);
In this case thenames will contain a list of the keys you are looking for. Here is the documentation for it:
http://underscorejs.org/#keys
keys_.keys(object)
Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]
I have an xml file that has been converted to the json listed below. I have been trying to figure out how to retrieve -Name and -Value from each of the Attributes with no luck. I'm guessing I need to create a sub-object that is equal to jsonobj.Media.Attribute[i], but am unable to access -Name or -Value once I do that. Any suggestions?
jsonobj= {
"Media": {
"Attribute": [
{
"-Name": "Keywords",
"-Value": "keyword value"
},
{
"-Name": "Title",
"-Value": "title value"
},
{
"-Name": "Description",
"-Value": "description value"
},
{
"-Name": "Author",
"-Value": "author value"
},
{
"-Name": "Copyright",
"-Value": "copyright value"
}
]
}
};
This will alert all the values you're looking for:
var list = jsonobj.Media.Attribute
for(index in list)
{
var obj = list[index];
var name = obj["-Name"];
var value = obj["-Value"];
alert(name);
alert(value);
}
Iterate jsonobj.Media.Attribute and use ['-Name'] to retrieve the value
for(var i = 0; i < jsonobj.Media.Attribute.length ; i++)
{
var attr = jsonobj.Media.Attribute[i]
alert(attr["-Name"]);
alert(attr["-Value"]);
}
You can not use - in the code, cause it is an operator, and JS will not recognize it as a method.
To solve your problem you can access the properties using other way.
Otherwise your code:
jsonobj.Media.Attribute[i].-Name
You can use:
jsonobj.Media.Attribute[i].["-Name"]
What is the same from calling, for an example:
jsonobj.["Media"].Attribute[i].["-Name"]
It can not identify key Attribute. Says can not read property 'Attribute' of undefined.