How to modify array? - javascript

I currently have an array of objects where each object has several properties. Example:
[
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
]
What would be the best way to convert this to an array of strings that contains the value from text? I had thought I might be able to do this using underscore.js:
headerText = _.pick(headerRow, 'text');
But I think that since the objects are in an array this will not work. My next idea is to just loop through each element in the array and push the text value to a new array, but i'm curious if anyone knows of a more elegant way to do this? Suggestions?

You're looking for Array#map:
var stringArray = headerRow.map(function(entry) {
return entry.text;
});
Live Example | Source
You don't even need Underscore, Array#map is part of ES5 and fully supported by V8, the JavaScript engine used by Node. Array#map calls the function you give it once for each entry in the array, and builds a new array from the return values of that function.
Or if you want to change the existing array, you can use Array#forEach:
headerRow.forEach(function(entry, index) {
headerRow[index] = entry.text;
});
Live Example | Source

Use _.map(headerRow, function(row) { return row.text; }). Array.map isn't available in IE < 9.

i'd use a foreach and just loop through it.
var jamie = [
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
];
var length = jamie.length,
element = [];
for (var i = 0; i < length; i++) {
element[i] = jamie[i].id;
// Do something with element i.
}
console.info(element);

This is a vanilla javascript version, which avoids using the not universally supported Array.map method.
// assign the array to a variable
var a = [
{ text: 'test1',
id: 1
},
{ text: 'test2',
id: 2
}
];
// loop through each item in the array, reassigning with it's text value
// not like this: for(i in a) a[i] = a[i].text
// but with a for loop based on the array length
var i;
for(i=a.length; i; i--){ a[i-1] = a[i-1].text; }
// check the results
console.log(a);
// ["test1", "test2"]

Related

How to modify remove extra data from object data [duplicate]

Given a JavaScript object:
var dataObject = {
object1: {id: 1, name: "Fred"},
object2: {id: 2, name: "Wilma"},
object3: {id: 3, name: "Pebbles"}
};
How do I efficiently extract the inner objects into an array? I do not need to maintain a handle on the object[n] IDs.
var dataArray = [
{id: 1, name: "Fred"},
{id: 2, name: "Wilma"},
{id: 3, name: "Pebbles"}]
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});
var dataArray = [];
for(var o in dataObject) {
dataArray.push(dataObject[o]);
}
ES6 version:
var dataArray = Object.keys(dataObject).map(val => dataObject[val]);
Using underscore:
var dataArray = _.values(dataObject);
With jQuery, you can do it like this -
var dataArray = $.map(dataObject,function(v){
return v;
});
Demo
ES2017 using Object.values:
const dataObject = {
object1: {
id: 1,
name: "Fred"
},
object2: {
id: 2,
name: "Wilma"
},
object3: {
id: 3,
name: "Pebbles"
}
};
const valuesOnly = Object.values(dataObject);
console.log(valuesOnly)
Assuming your dataObject is defined the way you specified, you do this:
var dataArray = [];
for (var key in dataObject)
dataArray.push(dataObject[key]);
And end up having dataArray populated with inner objects.
Using the accepted answer and knowing that Object.values() is proposed in ECMAScript 2017 Draft you can extend Object with method:
if(Object.values == null) {
Object.values = function(obj) {
var arr, o;
arr = new Array();
for(o in obj) { arr.push(obj[o]); }
return arr;
}
}
[Editing and updating my answer. The other answers seem to overlap with mine pretty much, but, I thought I have another ago and provide an alternative].
I present 3 solutions to this problem, based on:
Object.keys
Object.values
Object.entries
Objects.keys() solution:
let keys = Object.keys(dataObject); // ["object1", "object2", "object3" ];
let keysToResult = keys.map( e => dataObject[e] ); // [{"id":1,"name":"Fred"},{"id":2,"name":"Wilma"},{"id":3,"name":"Pebbles"}]
Object.values solution:
let values = Object.values(dataObject); // [{"id":1,"name":"Fred"},{"id":2,"name":"Wilma"},{"id":3,"name":"Pebbles"}]
Object.entries solution:
let entries = Object.entries(dataObject); // [["object1",{"id":1,"name":"Fred"}],["object2",{"id":2,"name":Wilma"}],["object3",{"id":3,"name":"Pebbles"}]]
let entriesToResult = entries.map( ([k,v]) => v ); [{"id":1,"name":"Fred"},{"id":2,"name":"Wilma"},{"id":3,"name":"Pebbles"}]
All three solutions have their own features.
Object.keys() returns an array with insufficient result. So, we use Array.prototype.map to top up each value in the array to get close to what we want. In general, we can think of Object.keys() combined with map as a mechanism to customize our result list with what we want.
Object.values() is interesting since it discards the key and just returns the results only. In fact, for this problem, this is perfect since the answer requires no further processing.
Object.entries() returns more than what we want since it returns both keys and values. We need to use map to customize our result. In fact, we need to cut out the excess information.
Object.keys(), Object.values() and Object.entries() are all very useful functions which is why I wanted to show all 3 as a solution to this problem. Depending on your specific use case, you may find one to a better fit to solving your problem.
Maybe a bit verbose, but robust and fast
var result = [];
var keys = Object.keys(myObject);
for (var i = 0, len = keys.length; i < len; i++) {
result.push(myObject[keys[i]]);
}
Object.values() method is now supported. This will give you an array of values of an object.
Object.values(dataObject)
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
In case you use d3. you can do d3.values(dataObject) which will give
I prefer to destruct object values into array:
[...Object.values(dataObject)]
var dataObject = {
object1: {id: 1, name: "Fred"},
object2: {id: 2, name: "Wilma"},
object3: {id: 3, name: "Pebbles"}
};
var dataArray = [...Object.values(dataObject)];
This one worked for me
var dataArray = Object.keys(dataObject).map(function(k){return dataObject[k]});

How to find the name property from an array of Objects

I am trying to get the value from an array of objects given the id, but I am not able to make it working. The problem is that I have an array of objects, so I don't know how to iterate over them. I know using the .map method could be a possible solution, but I'm new on this.
my method is that given a Id, it has to return me the name from the same object.
How could I iterate over them? I am using this actually:
getName(field_id: any): any {
var aux = 0;
var obj = this.customFields[aux].filter(function (obj) {
return obj.name === field_id;
})[0];
aux ++;
}
where aux is an iterator. Ofc is not working.
considering array containing the objects, you can just use the filter function, no neeed to use the indexer
var arr = [
{id: 1, name: "something"},
{id: 2, name: "something1"},
{id: 3, name: "something2"},
{id: 4, name: "something3"},
{id: 5, name: "something4"}
]
var id=3
var obj = arr.filter(function(obj) {
return obj.id === id;
})
console.log(obj[0].name)
I think your issue is that you compare the name with the id. If you want to avoid loops:
// This find the correct entry corresponding to the id you are looking for
var correctField = this.customFields.find(function(field) {
return field.id === field_id;
});
// Then you get the name from the entry
var nameToFind = correctField && correctField.name;
You might have to replace find depending on your browser support.
A way to replace it:
this.customFields.filter()[0]
You can simply use for loop as below
var arr = [{id:1,name:"abc"},{id:2,name:"pqr"},{id:3,name:"lmn"}]
function getName(id){
for(var i=0;i<arr.length;i++)
if(arr[i].id==id)
return arr[i].name;
return null
}
getName(2);// pqr

Remove a record in a Object Array jQuery

EDIT : Included more details
Hi I have a Object Array in jQuery which looks like this,
My question is how can I delete a record from that object array by columnheader as parameter. I know there is this
var result = $.grep(records, function(e){ return e.columnheader == currentheader; });
but grep i only used to check if there's a matching data based on currentheader that i passed in. What if I want to delete?
I want to delete a record on the fly as I am looping in that object array, lets I have. data contains all object arrays that is shown in the image.
$.each(data, function(key,value) {
// Let's say I want the code here to delete a record in the current object array that I'm looping into.
});
Thanks
You can use filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
arr = arr.filter(function(e) {
return e.columnheader !== currentheader;
});
Demo
var arr = [{
name: 'John Skeet',
rank: 1
}, {
name: 'T.J.Crowder',
rank: 10
}];
console.log(arr);
arr = arr.filter(function(e) {
return e.rank !== 10
});
console.log(arr);
UPDATE
I want the code here to delete a record in the current object array that I'm looping into
Changing a property from object in array.
var arr = [{
name: 'John Skeet',
rank: 1
}, {
name: 'T.J.Crowder',
rank: 10
}];
$.each(arr, function(index, obj) {
if (obj.rank === 10) {
arr[index].rank = 9;
}
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
You can use the JavaScript splice method to do it. First find the index of your object in the array then use the method like that :
your_array.splice(obj_index,0);
EDIT
The easy way but not optimized is to use a for loop to get the index, a better solution is to use linq.js to get the object, then your_array.indexOf(your_obj);
EDIT 2
You can download linq.js here Linq.js
You can use it like this:
function DelteObjFromArray(your_value){
var objToDelete = Enumerable.From(your_array).Where(function (x) { return x.your_property == your_value; }).FirstOrDefault();
var objIndex = your_array.indexOf(objToDelete);
your_array.splice(objIndex,1);
}

Javascript array object arrays

THis is going to sound like a stupid question but here it goes. I have a js array formatted like so
var locationID = [
{ ID: "ID1", location: "location1" },
{ ID: "ID2", location: "location2" },
{ ID: "ID3", location: "location3" },
];
I am trying to loop through the array
for(i = 0; i < locationID.length;i++){
var object = locationID[i];
}
I want to get both elements from the inner array so the ID and location. would I do this by object[0] or object["ID"] for example.
Also is there a more efficient way to do what I need to do like a for each loop or something along those lines.
Use object.ID or object['ID'].
Objects {} in JavaScript are associative, or named arrays. (Also known as a map in many languages. They are indexed by strings (in this case).
Arrays [], are indexed by integral numbers, starting from 0 and counting up to n-1, where n is the length of the array.
If you want to programmatically go through all the (key, value) pairs in each object, you can use this method.
Quotations (String Literals)
To reiterate my comment below about single and double quotes:
If you're talking about inside the [], no [,they're not important]. JavaScript treats single
quotes and double quotes pretty much the same. Both of them denote
string literals. Interestingly, you can use single quotes inside
double quotes or vice-versa: "I wanted to say 'Hello world!'" would be
a (single) valid string, but so would 'But I accidentally said "Goodbye".
This is an optimized loop based from the book of Nicholas Zackas (YAHOO performance chief). I am performing a cached array length to prevent re-evaluation of array length on every iteration of the loop. Please check jsperf.com. Also, native loop is always faster than method based loops jQuery.each and Array.prototype.forEach. This is also supported on browsers below ie8
var currentItem,
locationInfo = [
{ ID: "ID1", location: "location1" },
{ ID: "ID2", location: "location2" },
{ ID: "ID3", location: "location3" },
];
for (var i = 0, len = locationInfo.length; i < len; i++) {
currentItem = locationInfo[i];
console.log(currentItem.ID);//I prefer this because it shrinks down the size of the js file
console.log(currentItem["ID"]);
}
what you have already will return each of the objects in the JSON as you run the loop. What you need is something like
for(i = 0; i < locationID.length;i++){
var object = {locationID[i].ID, locationID[i].location};
}
Remember properties of objects are accessed by their keys since they are key-value pairs.
For loops are going to be your best bet as far as speed, here's how you'd do it with forEach (IE 9+)
locationID.forEach(function(location, i){
console.log(location['ID'])
console.log(location['location'])
});
jQuery make's it a little easier but runs slower
$.each(array, function(i, item){
});
http://jsperf.com/for-vs-foreach/75
Also here a useful link: For-each over an array in JavaScript?
You can use the forEach method, which make your code more cleaner.
See forEach
locationID.forEach(function(elm){
//Here, elm is my current object
var data = elm;
console.log(data.ID):
console.log(data.location);
});
EDIT :
Then for your second question, you should filter and map methods.
function findNamebyID(id){
//Filter by id and map the data to location
return locationID.filter(function(elm){
return elm.ID === id;
}).map(function(elm){
return elm.location;
})
}
Something as:
var location = locationID.reduce(function(ob, cur) {
ob[cur.ID] = cur.location;
return ob;
}, {});
The result you get is:
Object {ID1: "location1", ID2: "location2", ID3: "location3"}
Meaning you can do:
location.ID1 // location1
location.ID2 // location2
...
an alternative to your loop, would be to use the JavaScript for (.. in ..) since you aren't really using the iterator; it just adds fluff
for(i = 0; i < locationID.length;i++){
var object = locationID[i];
}
could be written as:
for (item in locationID) {
var object = item;
}

get index of element in array if it exists in another array/object

There are two arrays:
itemKeys: [
{
name: "REFOBJTYPE"
},
{
name: "REFOBJKEY"
}
...
]
itemValues: [
{
value: ""
},
{
value: ""
}
]
and an object
ref: {
REFOBJTYPE: 1,
REFOBJKEY: 2,
}
They are fixed and the structure itself cannot be changed.
values of itemValues should be filled with values from ref object,
to get index we have to look up the itemKeys array.
The point of this question: I don't want to use 2 "for" loops to check for each key if it exists in ref. I WANT use JAVASCRIPT specific features like maybe "indexOf", so:
is the ANY OTHER way, rather than TWO FOR-LOOPs to complete this task?
Please don't question why I need this, why don't I like 2 loops. Obviously under any implementation "behind" it will be 2 loops.
I'm not sure if this is what you meant, but if you loop over the itemKeys array, you can easily look up the value associated with the key in the ref object, and then write that out to the itemValues array in one loop.
for (var i = 0; i < itemKeys.length; i++) {
var key = itemKeys[i].name;
var value = ref[key];
itemValues[i].value = value;
}

Categories

Resources