Related
I have an array object as mentioned below;
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
I would like to extract the values of dateformat into a separate array, e.g.:
var dateArray=["apr1","apr2","apr3"];
var score=[1,2,3];
I am using a for loop to extract the index but I'm not able to get the values.
Use map to iterate over the initial array objects and return the item you want.
var myArray=[{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}];
var dateArray = myArray.map(function(obj){return obj.dateformat;}),
score = myArray.map(function(obj){return obj.score});
console.log(dateArray);
console.log(score);
Here's the answer as a simple loop.
var dateArray = new Array(myArray.length);
for(var i = 0; i < myArray.length; ++i) {
var value = myArray[i];
var dateValue = value.dateformat;
dateArray[i] = dateValue;
}
You can accomplish the same using the map function:
var dateArray = myArray.map(function(value) { return value.dateformat; });
Create the empty arrays, and use forEach with an argument of 'element' (which represents each object in the array) and push esch of the properties of each object into the required array.
var dateArray=[];
var score=[];
var myArray=[
{dateformat:"apr1", score:1},
{dateformat:"apr2",score:2},
{dateformat:"apr3",score:3}
];
myArray.forEach(function(element) {
dateArray.push(element.dateformat);
score.push(element.score);
});
console.log(dateArray); //gives ["apr1","apr2","apr3"]
console.log(score); //gives ["1","2","3"]
You could use a single loop approach of the given array and iterate the keys and push the values to the wanted arrays.
var myArray = [{ dateformat: "apr1", score: 1 }, { dateformat: "apr2", score: 2 }, { dateformat: "apr3", score: 3 }],
dateArray = [],
score = [];
myArray.forEach(function (target, keys) {
return function(a) {
keys.forEach(function(k, i) {
target[i].push(a[k]);
});
};
}([dateArray, score], ['dateformat', 'score']));
console.log(dateArray);
console.log(score);
If only you don't want to hard code the variables, you could use Array#forEach and Object.keys to store each unique key values inside e.g. array.
Note: It doesn't matter how many keys do you have in your objects, following solution will always return you the right output. Mind that you don't even have to initially declare new variables.
var myArray = [{dateformat:"apr1", score:1},{dateformat:"apr2",score:2},{dateformat:"apr3",score:3}],
obj = {};
myArray.forEach(v => Object.keys(v).forEach(function(c) {
(obj[c] || (obj[c] = [])).push(v[c]);
}));
console.log(obj);
I know it's simple, but I don't get it.
I have this code:
// My object
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
nietos.push(nieto.label);
nietos.push(nieto.value);
If I do this I'll get a simple array:
["Title", "Ramones"]
I need to create the following:
[{"01":"Title", "02": "Ramones"}]
How can I use push() to add the object into the nietos array?
You have to create an object. Assign the values to the object. Then push it into the array:
var nietos = [];
var obj = {};
obj["01"] = nieto.label;
obj["02"] = nieto.value;
nietos.push(obj);
Create an array of object like this:
var nietos = [];
nietos.push({"01": nieto.label, "02": nieto.value});
return nietos;
First you create the object inside of the push method and then return the newly created array.
can be done like this too.
// our object array
let data_array = [];
// our object
let my_object = {};
// load data into object
my_object.name = "stack";
my_object.age = 20;
my_object.hair_color = "red";
my_object.eye_color = "green";
// push the object to Array
data_array.push(my_object);
Using destructuring assignment (ES6)
const nieto = {label: 'title', value: 'ramones' }
const modifiedObj = {01: nieto.label, 02: nieto.value}
let array = [
{03: 'asd', 04: 'asd'},
{05: 'asd', 06: 'asd'}
]
// push the modified object to the first index of the array
array = [modifiedObj, ...array]
console.log(array)
If you'd like to push the modified object to the last index of the array just change the destructured array ...array to the front.
array = [...array, modifiedObj]
Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.
If you are willing to push properties or value into one object, you need to access that object and then push data into that.
Example:
nietos[indexNumber].yourProperty=yourValue; in real application:
nietos[0].02 = "Ramones";
If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.
Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).
This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]
Then push property and value into that like this:
myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";
I'm not really sure, but you can try some like this:
var pack = function( arr ) {
var length = arr.length,
result = {},
i;
for ( i = 0; i < length; i++ ) {
result[ ( i < 10 ? '0' : '' ) + ( i + 1 ) ] = arr[ i ];
}
return result;
};
pack( [ 'one', 'two', 'three' ] ); //{01: "one", 02: "two", 03: "three"}
The below solution is more straight-forward. All you have to do is define one simple function that can "CREATE" the object from the two given items. Then simply apply this function to TWO arrays having elements for which you want to create object and save in resultArray.
var arr1 = ['01','02','03'];
var arr2 = ['item-1','item-2','item-3'];
resultArray = [];
for (var j=0; j<arr1.length; j++) {
resultArray[j] = new makeArray(arr1[j], arr2[j]);
}
function makeArray(first,second) {
this.first = first;
this.second = second;
}
This solution can be used when you have more than 2 properties in any object.
const nieto = {
label: "Title",
value: "Ramones"
}
let nietos = [];
let xyz = Object.entries(nieto)
xyz.forEach((i,j)=>{
i[0] = `${(j+1).toLocaleString("en-US", {
minimumIntegerDigits: 2,
useGrouping: false,
})}`
})
nietos.push(Object.fromEntries(xyz))
Two problems consider the following object:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
Why does my cars array have length of 0? Do i have to update the length property manually?
Why is my stringified object empty when it has parameters in it i'm assuming it is tied into the length property?
Fiddle:https://jsfiddle.net/wcd7f8Lz/
car is initialized as an array, but used as an Object. and an object does not have length attribute...
To get the length of an object, you can do ̀̀̀̀Object.keys(obj).length (get the keys list, and because it is an array, it have a length).
But the problem is also that you initialize cars as an array, but use it as Object...
see docs here:
http://www.w3schools.com/js/js_arrays.asp
http://www.w3schools.com/js/js_objects.asp
The solution is to initialize it as Object:
//new obj
var obj = {};
obj['cars'] = {}; //And other object
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
But if you want instead a simple array:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars'][1] = "toyota";
obj['cars'][0] = "mazda";
console.log(obj);
console.log(JSON.stringify(obj));
The syntax is ̀array[identifier] = value;
(and not ̀̀̀̀̀array[value] = identifier)
I've updated the fiddle.
obj.cars.length is 0, because you don't push new items in array, but change it properties:
var obj = {};
obj.cars = []; // obj.cars is empty array
obj.cars.toyota = 1; // obj.cars is empty array with a new property toyota
obj.cars.push('mazda'); // obj.cars is array with a new property toyota and one element mazda
console.log(obj.cars instanceof Array,
obj.cars.length,
Object.keys(obj.cars)); // output: true 1 ["toyota"]
Why you don't use it in this way?
var cars = [];
cars.push({name:'toyota', value:1});
cars.push({name:'mazda', value:0})
That's because you aren't using an array (despite declaring it with an array literal), you're using it as an object.
Arrays are just a special case of object, meaning they can have individual properties. These properties don't exist "in" the array but instead are properties "of" the array.
var arr = [1, 2, 3];
arr.thing = 'a';
console.log(arr.length); // 3
To add elements to an array, you should use push:
var arr = []; // length: 0
arr.push(1); // length: 1
If you want to be able to access an object both by name and index then you can combine push with custom properties.
var arr = [];
arr.push(0);
arr.mazda = 0;
I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)
I'm creating an array using "push"
so the result is [Object, Object]
in there the code looks like:
[Object, Object]
0: Object
type: Array[6]
1: Object
type: Array[4]
I would like to combine both object and get a result like this:
["Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl", "Jim", "Issac", "Lee", "Won"]
I have no idea to get this to work, any suggestion?
code sample:
dropdown: function(data) {
var arr = [];
$.each(data, function(key, value) {
arr.push({
type: value.type
});
});
}
You can concatenate one array onto another with concat.
arr = arr.concat(otherArr);
Note that concat creates a new array, leaving the original unchanged, which is why you have to re-assign it.
Note - for three arrays, you can just keep passing them in.
var arr1 = [0,1];
var arr2 = [2,3];
var arr3 = [4,5];
arr1 = arr1.concat(arr2, arr3);
console.log(arr1);
Fiddle
EDIT
You mentioned having dynamic arrays. I'm not sure what you mean by that, but I'll note that if you have an arbitrary array of arrays, and you want them all concated, you can do this
var arr1 = [0,1];
var arr2 = [2,3];
var arr3 = [4,5];
var otherArrays = [arr2, arr3];
arr1 = Array.prototype.concat.apply(arr1, otherArrays);
console.log(arr1);
FIDDLE
Use concat, like this
arr1=["apple","orange","pineapple","pomegranate"];
arr2=["pizza","candy","chocolate","tasty"];
arr3=["food","drink"];
concatted=arr1.concat(arr2).concat(arr3);
You can keep chaining together arrays like that for as long as you want, until you run out of memory
Alternatively, you can just do this
concatted=arr1.concat(arr2,arr3);
If you want to remove duplicates, you can use this
Array.prototype.removeDuplicates=function(){
var newArray=[];
for(var i=0;i<this.length;i++){
if(newArray.indexOf(this[i])==-1){
newArray.push(this[i]);
}
}
return newArray;
}
A simple loop:
var result = [];
for (var i = 0; i < objects.length; i++) {
$.merge(result, object[i].type);
}
Since you specified that you can use jquery, check out the merge() function: http://api.jquery.com/jquery.merge/