JS: select the same attribute in every object in an array - javascript

If I have an array of objects, for example:
var cars = [{name:"Geronimo", color:"red"},{name:"Ronaldo",color:"green"}]
Is there a simple way Im not seeing to select all the "color" attributes? So that I would get:
"red", "green"
So say something like (INVENTED):
console.log(cars[selectingallobjects].name)
Thanks in advance!

There isn't a ready way of doing that, you need to iterate to get the values.
You can use .map(), an Array method that creates a new array based on the values returned from the function.
It can be done in a single line.
See below:
var cars = [{name:"Geronimo", color:"red"},{name:"Ronaldo",color:"green"}]
let result = cars.map(car => car.color)
console.log(result)

you can use map to do the following, it loops for every object in the array.
var cars = [{name:"Geronimo", color:"red"},{name:"Ronaldo",color:"green"}]
cars.map((eachObject)=>{
console.log(eachObject.color);
});

Using for-loop and take only color property
var cars = [{name:"Geronimo", color:"red"},{name:"Ronaldo",color:"green"}]
var carNames = []
for(car of cars){
carNames.push(car['color'])
}
console.log(carNames)// [ "red", "green" ]
use map which is method creates a new array:
var carNames = cars.map(car=>car.color)

Related

How to collect / make new array by existing arrays label wise?

How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console

How can I split a string and then push something into the resulting array?

I have this string:
var fruits = "banana,apple";
And I'm trying to add fruits to it by converting it to an array and then pushing the new fruit like this:
var newFruit = "orange";
fruits
.split(",")
.push(newFruit);
But this doesn't work because fruits.split(",") doesn't seem to return a "normal" array, i.e I can't perform push() on it.
Is this somehow possible?
split does return a normal array. You are successfully calling push on it.
The problem is that you are then discarding the array so you can't do anything further with it.
Since push doesn't return the array itself, you have no way of using the array for anything further after calling push on it.
concat returns a new array that contains the additional values, but you would still have to do something with the array afterwards.
var fruits = "banana,apple";
var newFruit = "orange";
var myArray = fruits
.split(",")
.concat(newFruit);
console.log(myArray);
Array.prototype.push returns the new length of the array:
Return value:
The new length property of the object upon which the method was
called.
MDN Source
Also, you're not storing your new value. If you want to use push, here's how you'd do it:
var fruits = "apple,banana";
var newFruits = fruits.split(","); // Store the new array
newFruits.push("orange"); // Add the new item
console.log(newFruits);
If you want to do it in one line, you can use concat:
var fruits = "apple,banana";
var newFruits = fruits
.split(",") // Convert string to array
.concat("orange"); // Create a new array joined with value
console.log(newFruits);
push returns the new length of the array, because you are not saving it then you cant see the new array(after push)
try doing it in two lines:
newFruits = fruits.split(",");
newFruits.push(newFruit);

add object to another array of objects in javascript

Can any one please help me how to add objects to another array of Objects
myArray = [
{
"A" :{
values
},
"B" :{
values
},
"C":{
values
}
}
]
another Object:
{
"D":{
values
},
"E":{
values
}
}
I want to add next objects like D and E to My Array of First Object.
it shuold be like this
[
{
"A":{},
"B":{},
"C":{},
"D":{},
"E":{}
}
]
Cna you help me any one how to add this objects
Thanks in Advance
According to my understanding you have one array of object i.e.
myArray = [{"A" :{},"B" :{},"C":{}}]
and you want to add some property in that object so just use
myArray[0].D={};
myArray[0].E={};
console.log(myArray[0]);
And if You want to add more objects in Array use push method
var obj={"A1" :{},"B1" :{},"C1":{}}
if you want to add in myArray then use
myArray.push(obj);
yours array of object will be
myArray = [{"A" :{},"B" :{},"C":{}},
{"A1" :{},"B1" :{},"C1":{}}]
Hope it clears yours doubt.
try something like this
myarray=[{"A":"e1"},{"B":"e2"},{"C":"e4"}];
var obj={"D":"e5"};
myarray.push(obj);
alert(myarray[3].D)
will alert e5
DEMO
Update :
myarray=[{"A":"e1"},{"B":"e2"},{"C":"e4"}];
var obj={"D":"e6","E":"e9"};
myarray.push(obj);
alert(myarray[3].F)
will alert e9

Check if an object has a key in javascript

I have two arrays of objects, and I want to filter the first one according to whats on the second one. Here's an example:
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
So in this case what I want to return is an array with the objects that have id's 23 and 54 of the first array, with all its possible properties (in this case, title).
Could you give me any hint that could help me?
Get a list of the indexes you want to search on using map:
var indexes = ary2.map(function (el) {
return el.id;
});
filter the results based on the list of indexes:
var result = ary1.filter(function (el) {
return indexes.indexOf(el.id) > -1;
});
DEMO
This might help you.
Loop through ary2, building up an array of each id value (let's call this array existingIds).
After that loop, now loop through ary1. For each item in ary1, check to see if the id value exists in the existingIds array that we just built up. If it does, append the current item to a result array.
I could write the code for you, but it will be a better learning experience if you first try this yourself :)
Might as well make use of some functional programming built into javascript.
filteredResults = ary1.filter(function(ele){
return (ary2.map(function(idobj){return idobj.id;}).indexOf(ele.id)>-1)
})
filter(function) will iterate through each element of an array, passing it through a callback function. From within that callback iff a true is returned, that value is kept. If false, that value is filtered out.
Also map(function) will iterate through each element of an array passing a callback value as well. All values returned from map callback will be injected into the result. So we can take the id from each element in ary2 and return it in the map function.
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
//Filter for the available ID's, store the resulting objects in a new array
filteredResults = ary1.filter(function(ele){
//map creates an array of just ID's
return (ary2.map(function(idobj){return idobj.id;}).indexOf(ele.id)>-1)
})
//now do whatever you were planning on doing with your results/
var res = document.getElementById("results");
filteredResults.forEach(function(ele){
res.innerHTML+="<li>{id:"+ele.id + ",title:" +ele.title+"}</li>"
})
console.log(filteredResults);
<ul id="results"></ul>
try this:
var ary1 = [{id: 23, title: 'blabla'},{id:43, title: 'bleble'}, {id:54, title:'blibli'}];
var ary2 = [{id:23},{id:54}, {id:65}];
var newary=[];
for(x in ary1){
for(y in ary2){
if(ary1[x].id == ary2[y].id){
newary.push(ary1[x]);
}
}
}
console.log(newary);// here newary will be your return newary;

How can I add an array to an array of arrays using jQuery?

I have an array, as below:
var cString = [
['1','Techdirt','www.techdirt.com'],
['2','Slashdot','slashdot.org'],
['3','Wired','wired.com']
];
to this array I want to add another in the same format:
var test = ['4','Stackoverflow','stackoverflow.com']
I've tried using:
var newArray = $.merge(cString, test);
But console.log(newArray); outputs:
[►Array,►Array,►Array,'4','Stackoverflow','stackoverflow.com']
So I'm assuming that I'm missing something obvious. Or attempting something stupid...help?
jQuery is not needed for this. Just use the Array's .push() method to add it to the main array.
var test = ['4','Stackoverflow','stackoverflow.com']
cString.push( test );
What $.merge() does is it walks through the second array you pass it and copies its items one by one into the first.
EDIT:
If you didn't want to modify the original array, you could make a copy of it first, and .push() the new Array into the copy.
var cString = [
['1','Techdirt','www.techdirt.com'],
['2','Slashdot','slashdot.org'],
['3','Wired','wired.com']
];
var test = ['4','Stackoverflow','stackoverflow.com']
var newArray = cString.slice();
newArray.push( test );
In addition to push as described by patrick, if you want to create a new list rather than changing the old, you can add arrays together with Array#concat:
var newArray= cString.concat([['4','Stackoverflow','stackoverflow.com']]);
you can use merge function like this
var newArray = $.merge($.merge([], cString), test);

Categories

Resources