I have an object:
var obj =
[
{
"value": "aep",
"label": "AEP"
},
{
"value": "cap",
"label": "CAP"
},
{
"value": "casl",
"label": "CASL"
} ]
And I want to convert the values of the labels ONLY into an array so that the end result is:
["AEP", "CAP", "CASL"]
How do I only get the label values converted in an array?
First: obj is not an object, it is an array since the parent brackets are [] and not {}. I will, however, keep the name the same. This might have caused you some confusion, e.g.
var object = {};
var array = [];
var arrayOfObjects = [{},{},{}];
var objectOfArrays = {array1: [],array2: [],array3: []};
To loop an array you can use a for loop:
// new array
var newArray = [];
// iterates over each index in the array
for(var i=0; i<obj.length; i++) {
// Access the specific index, then access its `label` property
// Push into `newArray`
newArray.push(obj[i].label);
}
console.log(newArray);
Codepen: http://codepen.io/theblindprophet/pen/RRxVba
Using a for loop
var out = [];
for (var i = 0, len = obj.length; i < len; i++) {
out.push(obj[i].label);
}
console.log(out);
Its simple. You can use map function of javascript array
var obj =
[
{
"value": "aep",
"label": "AEP"
},
{
"value": "cap",
"label": "CAP"
},
{
"value": "casl",
"label": "CASL"
} ]
var arr = obj.map(function(data){return data.value});
This is a functional solution and not the most straightforward one, you may want to refer to #theblindprophet's answer for the imperative approach to this problem.
Pretty easy task to be done in a functional way:
var labels = obj.map(function(inner) { return inner.label });
How does one approach such a problem: You need to think of how to transform the data you have to the data you want. In this case you have an Array of Objects and you want to transform this Array of Objects to an Array of Strings placed inside that Object.
The above code iterates over the Array and returns the value you want for the current element of the Array, building a new Array in the course (map)
Related
I have an array, say
var arr = ["id", "currency", "region", "status"]
How can I map the above to an object literal, as below?
var columns = [
{ key:"id", headerRenderer:"id" },
{ key:"currency", headerRenderer:"currency" },
{ key:"status", headerRenderer:"region" },
{ key:"region", headerRenderer:"status" }
];
Thanks in advance!
One solution is to use Array#map method.
The map() method creates a new array with the results of calling a provided function on every element in this array.The provided function is a callback.
So, as I said above map method provided callback function once for each element in an array, in order, and constructs a new array from the results. The elements from the result array are objects, like this: {"key":item, "headerRenderer":item}.
var array = ["id", "currency", "region", "status"]
var columns=array.map(function(item){
return {
"key":item,
"headerRenderer":item
}
});
console.log(columns);
The map method on the Array prototype allows you to apply a function to every element in an array, thereby effectively abstracting iteration for simple cases. Your case is simple, because the content of any entry in result is completely specified by its corresponding entry in arr, which means you can "map"
"id" --> { key: "id", headerRenderer: "id" }
Using map you can solve your problem in just one line (provided your environment supports ES6):
var arr = ["id", "currency", "region", "status"]
var result = arr.map(key => ({ key, headerRenderer: key }));
console.log(result);
var columns = [];
var array = ["id", "currency", "region", "status"];
for (var i = 0, len = array.length; i < len; i++) {
columns.push({
key: array[i],
headerRenderer: array[i]
});
}
Normally .map() is the way but another functional approach would be to use a tail call recursive map as follows;
var arr = ["id", "currency", "region", "status"],
mapo = (a, r=[]) => a.length ? mapo(a.slice(1),r.concat({key:a[0],headerRenderer:a[0]})) : r;
console.log(mapo(arr));
I am trying to get values from the following object. The for loop works in one of the objects but won't in the other javascript object. I was wondering what the difference and how can I get it to work in the other object?
Object 1:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
}
];
Object 2:
{
"4dd5a49e366": {
"name" : "bar",
"bar" : "sit",
"date": "2016-08-03T04:48:04.283Z"
},
"519c5056af2": {
"name" : "lorem",
"bar" : "ipsum",
"date": "2016-09-03T04:48:04.283Z"
}
}
I want to do a search for items where name attribute is matching some search_term. And return the items.
Here is the search for loops am using.
function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var i in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('o'));
This works for the first object and not for the second. How can I get it to work for the second?
The first variable is an array of objects. Since it is an array you can use all array methods on it.
Second one is an object with keys 4dd5a49e366 & 519c5056af2 which in turn are again object and have few properties.
You cannot use array methods on this second object
how can I get it to work in the other object?
Hope this snippet will be useful
var myObject = {
"4dd5a49e366": {
"name": "bar",
"bar": "sit",
"date": "2016-08-03T04:48:04.283Z"
},
"519c5056af2": {
"name": "lorem",
"bar": "ipsum",
"date": "2016-09-03T04:48:04.283Z"
}
}
// a function to accept the name value
function findByName(name) {
var thisObject = "";
for (var keys in myObject) { // looping over objects
var getThisObject = myObject[keys];
if (getThisObject.name === name) { // Checking if name matches
thisObject = myObject[keys]; // assigning the object to a variable
}
}
return thisObject // return that variable
}
var getMyObject = findByName('bar');
console.log(getMyObject)
JSFIDDLE
EDIT
if I enter just findByName('b'); it should return results that the
full name
You need to use indexOf to find if this name value contains the specific character.
Use an array to store all the relevant object where the name value contains this specific character.Return that array from the function.
function findByName(name) {
var thisObject = [];
for (var keys in myObject) {
var getThisObject = myObject[keys];
if (getThisObject.name.indexOf(name)!==-1) {
thisObject.push(myObject[keys]);
}
}
return thisObject
}
var getMyObject = findByName('b');
JSFIDDLE 2
I suggest you do some reading on JavaScript Object literals and Arrays. The first example is an array of objects. The second is just an object. Two completely different data structures.
I have two object which contain some similar properties. I want to merge those two object in one object and also want to rename the similar properties from both objects.
var selectedEntity = {"UsageS":"123","DateS":"2016","IsEstimeated":"True"};
var ComapareEntity = {"UsageC":"124","DateC":"2015","IsEstimeated":"False"}
Result = {"UsageS":"123","DateS":"2016","IsEstimeatedS":"True","UsageC":"124","DateC":"2015","IsEstimeatedC":"False"};
Please suggest some solution using lodash.
Try to put these two objects in a json array, so that index can used to name duplicate keys
var selectedEntity = {
"UsageS": "123",
"DateS": "2016",
"IsEstimeated": "True"
};
var ComapareEntity = {
"UsageC": "124",
"DateC": "2015",
"IsEstimeated": "False"
}
var toLoopArray = [selectedEntity, ComapareEntity]
var resultantObject = {};
toLoopArray.forEach(function(item, index) {
for (var keys in item) {
if (!(resultantObject.hasOwnProperty(keys))) {
resultantObject[keys] = item[keys]
} else {
resultantObject[keys + index] = item[keys]
}
}
})
console.log(resultantObject)
JSFIDDLE
I have an array of objects that looks like the image below. Is there a way by which I can have an array that contains unique objects with respect to id ? We can see below that the id are same at index [0] and index [2].
Is there a way that I can get an array containing objects with unique id and the first object from the last index is added to the unique array rather than the first object. In this case, Object at index[2] should be added instead of object at index[0]:
To get an array of "unique" objects(with last index within the list) for your particular case use the following approach (Array.forEach, Array.map and Object.keys functions):
// exemplary array of objects (id 'WAew111' occurs twice)
var arr = [{id: 'WAew111', text: "first"}, {id: 'WAew222', text: "b"}, {id: 'WAew111', text: "last"}, {id: 'WAew33', text: "c"}],
obj = {}, new_arr = [];
// in the end the last unique object will be considered
arr.forEach(function(v){
obj[v['id']] = v;
});
new_arr = Object.keys(obj).map(function(id) { return obj[id]; });
console.log(JSON.stringify(new_arr, 0, 4));
The output:
[
{
"id": "WAew111",
"text": "last"
},
{
"id": "WAew222",
"text": "b"
},
{
"id": "WAew33",
"text": "c"
}
]
The best way to do this is to modify your data structure into an object itself where each key is one of the IDs:
{
"WadWA7WA6WAaWAdWA...": {
"text": "birla"
},
"WadWA...": {
"test": "ab"
}
}
and so forth. If the data comes from a source formatted that way, you can always map the array of results to this format.
You could create a hash using the id as the key and keeping the value as the entire object:
var myHash = new Object();
var i;
for(i = 0; i < yourArray.length; i++) {
var yourObjId = yourArray[i][id];
myHash[yourObjId] = yourArray[i];
}
You would be left with a hash myHash containing objects with unique id's (and only the last object of duplicates would be stored)
Try this: just add to a new object using id as the key
var arr = [{id:'123', text: 'a'}, {id:'234', text: 'b'}, {id:'123', text: 'c'}];
var map = new Object();
for(var i in arr){ map[arr[i].id] = arr[i]; }
var newArr = [];
for(var i in map){ newArr.push(map[i]); }
newArr shall contain the 2nd and 3rd object.
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.