I am using AngularJS and I have a problem as below:
I have created an Object whose properties are arrays. For example:
$scope.myObject = {
import: [ object1, object2,...,objectN ],
export: [ object1', object2',...,objectN' ],
...
}
Now I want to create a new array which concats all arrays from myObject properties so that I can display them in HTML view with ng-repeat.
This is my Plnk sample code: http://plnkr.co/edit/Ca8OX7kX8wV8JmRYJCzS?p=preview
Please help me. Thanks.
With underscore or lodash :
_.flatten(_.values($scope.myObject));
See fiddle
I've added also a plain JS (EcmaScript 5+) method :
$scope.myObjectJS = [];
Object.keys($scope.myObject).forEach(function(key) {
$scope.myObjectJS = $scope.myObjectJS.concat($scope.myObject[key]);
});
The fact that I use Object.keys(obj) instead of for (var key in obj) exempts us to check for hasOwnProperty.
If I understand your question right this should work.
var newArr = [];
for(var key in $scope.myObject){
newArr = newArr.concat($scope.myObject[key]);
}
Related
This question already has answers here:
Copy array by value
(39 answers)
Closed 8 years ago.
I have an array example fruit . I'd like to copy it as array fruits2, without keeping reference.
As in the following example reference is kept so fruits is modified.
var fruit = function (name){
this.name = name;
}
var fruits = [];
fruits.push(new fruit('apple'));
fruits.push(new fruit('banana'));
fruits.push(new fruit('orange'));
var fruits2 = fruits;
fruits2.length = 0;
console.log(fruits);
http://jsfiddle.net/vkdqur82/
Using JSON.stringify and JSON.parse does the trick but the objects in fruits2 are not any longer of type fruit but are of general type object
var temp = JSON.stringify(fruits);
var fruits2 = JSON.parse(temp);
I would like to know an alternative approach which would keep inner object of fruit.
Use slice: var fruits2 = fruits.slice(); should do it.
Your jsFiddle, modified
See also: MDN
**Edit. I was a bit lazy, let's correct my answer to make up for that.
For an Array of just values slice is perfect. For an Array of objects or arrays or a mix of values/objects/arrays, the Array and Object elements of the Array to clone need cloning too. Otherwise they will be references to the original arrays or objects (so: not copies) and a change of one [of these references of arrays or objects] will be reflected in all 'clones' containing a reference to it.
To clone an Array of Arrays/Objects/mixed values Array.map is your friend. There are several methods to think of:
creating a new instance with old data
var fruits1 = fruits.map(function(v) {return new Fruit(v.name);});
using JSON
var fruits2 = fruits.map(function(v) {return JSON.parse(JSON.stringify(v));});
create and use some cloning method
var fruits3 = fruits.map(function(v) {return cloneObj(v);});
In case 3, a method for cloning could look like:
function cloneObj(obj) {
function clone(o, curr) {
for (var l in o){
if (o[l] instanceof Object) {
curr[l] = cloneObj(o[l]);
} else {
curr[l] = o[l];
}
}
return curr;
}
return obj instanceof Array
? obj.slice().map( function (v) { return cloneObj(v); } )
: obj instanceof Object
? clone(obj, {})
: obj;
}
Using this cloneObj method, Array.map is obsolete.
You can also use var fruitsx = cloneObj(fruits);
The jsFiddle from the link above is modified to demonstrate these methods.
For Array.map, see again MDN
slice can do the trick.
You can also use .map but .slice is normally faster.
var copy = fruits.map(function(item) {return item});
Hope it helps
You can declare a new array and use concat method, so that you concat all values from your array to the new array. Something like this:
var x = ["a","b"];
var a = [];
a = a.concat(x);
console.log(a);
I edited my poor answer.
Best regards.
{
"ma.addEvents":{
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
I don't understand how I can create object like "ma.addEvent"
the "dot" is a problem here.
Try this
var x = {
"ma.addEvents":{
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
If you want to access, you have to use [] notation (. notation won't work, because of dots in keys) like
console.log(x["ma.addEvents"]["ma.id"])
You might want to use a square bracket notation:
var yourObject = {};
yourObject['ma.addEvents'] = {};
...and so on. Print the ma.addEvents attribute using
console.log(yourObject['ma.addEvents'])
You can use this:
var json_string = "{\"ma\.addEvents\":{\"ma\.id\":\"my-id\",\"ma\.eventIds\":[\"eventID1\",\"eventID2\"]}}";
The code above, when parsed to json (JSON.parse), will retrieve the same object that appears on your question.
Hope this helps,
Regards,
Marcelo
var obj = {
"ma.addEvents": {
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
}
}
Depends on what part you would like to add dynamically.
var obj = {};
obj["ma.addEvents"] = {
"ma.id":"my-id",
"ma.eventIds":[
"eventID1",
"eventID2"
]
};
obj["ma.addEvents"]["ma.eventIds"].push("someotherEvent");
Please take a look at the documentation for accessors.
ma must be defined before you create ma.addEvents etc. The syntax might look like this:
// `ma` is an object
var ma = {
// It contains an object called `addEvents`
addEvents: {
// Which contains a string `id` and an array `eventIds`
id: "my-id",
eventIds: [
"eventId1",
"eventId2"
]
}
}
To create a blank object in ma, you could use the 'dot' syntax:
ma.newObject = {};
or square bracket notation:
ma["newObject"] = {};
I'm not entirely sure what your question is, are you looking to parse that JSON or to learn Javascript object syntax?
Simple question, but I cannot find a solution.
I have an array of objects.
I also have a reference to an object from this array.
I want to delete the object from the array.
How to do it in Javascript (without comparing object properties)?
PS It is easy to do it in C# (using List collection)
List<SomeObject> list = ........ ;
SomeObject element = ......... ;
list.Remove(element);
You can use indexOf to get the index of the object and splice to remove it from the array:
var arr = [ { name: 0}, { name : 1 } , {name : 2 } ];
var myObj = arr[1];
arr.splice(arr.indexOf(myObj),1);
console.log(arr);
There is no way to do this with arrays directly. You will have to find or roll your own implementation of an collection which supports similar operation.
I'm trying to create a copy of existing array and remove some items from array copy without impacting the original. I've tried this :
var new_arr = old_arr; //when I remove from new array the items from old array are also removed
How do I create entirely new copy of the existing array?
Update :
When I do this :
var new_arr = old_arr.slice();
then later :
new_arr[0].shift();
new_arr[1].shift();
The items from old_array get removed. This is a two dimensional array.
You can use two methods, this:
function clone (src) {
return JSON.parse(JSON.stringify(src));
}
or this:
var newArray = oldArray.slice();
A newer solution to do this is to use 'from' like this:
const newArr = Array.from(oldArr);
But this is a shallow copy and if nested elements are mutated they will project in the new created array with from. Best solution then would be to use
const newArr = JSON.parse(JSON.stringify(oldArr));
but also that method doesn't ensure all. If for example an element of the array contains a function like n => ++n then it will be null after using the JSON methods so best solution is deepClone and for that full explanation I refer to
Creating JavaScript Arrays
Using Yoshi answer you can extend Array prototype (just a simple helper):
Array.prototype.clone = function() {
return this.slice(0);
}
In Javascript, a two-dimensional array is just an array of arrays. Therefore, cloning one dimension is not enough. We also need to clone all the sub-dimension arrays. Here’s how we do it:
function cloneGrid(grid) {
// Clone the 1st dimension (column)
const newGrid = [...grid]
// Clone each row
newGrid.forEach((row, rowIndex) => newGrid[rowIndex] = [...row])
return newGrid
}
// grid is a two-dimensional array
const grid = [[0,1],[1,2]]
newGrid = cloneGrid(grid)
console.log('The original grid', grid)
console.log('Clone of the grid', newGrid)
console.log('They refer to the same object?', grid === newGrid)
---
The original grid [ [ 0, 1 ], [ 1, 2 ] ]
Clone of the grid [ [ 0, 1 ], [ 1, 2 ] ]
They refer to the same object? false
Or if we take avantage of ES6 Array.map operation, we can make cloneGrid function even simpler:
const cloneGrid = (grid) => [...grid].map(row => [...row])
For more expanded answer read How to make a copy of an array in JavaScript
You can try .concat()
var old_arr = [1,2,3,4,5]
var new_arr = old_arr.concat()
console.log(old_arr) //1,2,3,4,5
console.log(new_arr) //1,2,3,4,5
new_arr.shift()
console.log(old_arr) //1,2,3,4,5
console.log(new_arr) //2,3,4,5
you may create a new array by using the spread operator. You can also find more about spread operator HERE.
cosnt oldArr = [{id: 1, name: 'Ali'}, {id:2, name: 'Raza'}];
cosnt newArray = [...oldArr];
console.log(newArray);
I'm hoping my question is using the correct terminology...
Can someone explain to me how I can perform the following:
If I have an array consisting of:
Object { id=1498, brandName="Booths", quality="Standard"}
Object { id=1499, brandName="Booths", quality="Standard"}
How can I iterate throughout that array and return another array of distinct 'keys'?
Ultimately I want an array which would return something like:
[id,brandName,quality] (but the original array is going to return different keys at different times.
Have I made sense?
You can use Object.keys:
var a1 = [{ id:1498, brandName:"Booths", quality:"Standard"},
{ id:1499, brandName:"Booths", quality:"Standard"}],
a1Keys = a1.map(function(a){return Object.keys(a);});
//a1Keys now:
[['id','brandName','quality'],['id','brandName','quality']]
The keys method is described #MDN, including a shim for older browsers
var a = {"a": 1, "b": "t" };
var keys = new Array();
for(var o in a){
keys.push(o);
}
console.log(keys)