I have an array which contains objects. How to output everything from the object to the markup?
I think I stuck in this part of code div_child.innerHTML
On output I got this cars[object Object] eleven times.
Should be like this:
img
car: 'Audi'
model: 'A6'
age: 2014
price: 20900
let cars = [];
cars[0] = {
img: 'assets/img/img-1.webp',
car: 'Audi',
model: 'A6',
age: 2014,
price: 20900
}
// and 9 another objects of cars
let div = document.createElement('div');
div.className = 'cars-list';
for (let key in cars) {
let div_child = document.createElement('div');
div_child.className = 'cars-list__item';
div_child.innerHTML = `${cars}` + `${cars[key]}`; // As I understood this is the root of problem
div.append(div_child);
}
document.body.append(div);
Why is using "for...in" for array iteration a bad idea?
I would use a map:
let cars = [{
img: 'assets/img/img-1.webp',
car: 'Audi',
model: 'A4',
age: 2014,
price: 20900
},{
img: 'assets/img/img-2.webp',
car: 'Audi',
model: 'A5',
age: 2014,
price: 20900
},{
img: 'assets/img/img-3.webp',
car: 'Audi',
model: 'A6',
age: 2014,
price: 20900
},
]
// and 9 another objects of cars
let div = document.createElement('div');
div.className = 'cars-list';
div.innerHTML = cars.map(car => `<div class="cars-list__item">${car.car}: ${car.model}</div>`).join("")
document.body.append(div)
Related
This question already has answers here:
Convert Array to Object
(46 answers)
Closed 26 days ago.
For example, I have the following array of objects:
[{id:1, name: Hana, age: 30}, {id:2, name: Sana, age: 20}, {id:3, name: Kana, age: 30}]
I want to convert it to an object of objects as following:
{0:{id:1, name: Hana, age: 30}, 1:{id:2, name: Sana, age: 20}, 2:{id:3, name: Kana, age: 30}}
Using Object's pre built method assign you can achieve this.
Object.assign({}, yourObject);
No need to iterate through the Array unnecessary.
You can easily achieve the result, using a simple map function and store the result in an object as a key:value pair
const data = [{id:1, name: 'Hana', age: 30}, {id:2, name: 'Sana', age: 20}, {id:3, name: 'Kana', age: 30}]
const resultObj = {}
data.map((obj,index) => resultObj[index] = obj)
console.log(resultObj)
You can map that array and get its unique value (in this case i have taken id as key) then map it according you want to display array.
Here is an example to do that.
var arr = [{
id: 1,
name: 'Hana',
age: 30
}, {
id: 2,
name: 'Sana',
age: 20
}, {
id: 3,
name: 'Kana',
age: 30
}]
var mapped = arr.map(item => ({
[item.id]: item
}));
var newObj = Object.assign({}, ...mapped);
console.log(newObj);
How would I loop over two objects and only return a list of the keys & values that were different?
let list = [];
let previousObject = {
key: 'key_1',
name: 'Previous name',
age: '30',
location: '12345 Main St.',
height: '77',
weight: '215',
...
}
let newObject = {
key: 'key_1',
name: 'New name',
age: '25',
location: '54321 Main St.',
height: '77',
weight: '195',
...
}
I would like the list to return...
list = [{ name: 'New name', age: '25', location: '54321 Main St.' }]
Things to consider:
The previousObject might contain more keys than the newObject
Checking for these differences might happen more than once per user session
In your example list is an array with only one object containing all the differences. To get that object, you can do this:
let list = [];
let previousObject = {
key: 'key_1',
name: 'Previous name',
age: '30',
location: '12345 Main St.',
height: '77',
weight: '215',
}
let newObject = {
key: 'key_1',
name: 'New name',
age: '25',
location: '54321 Main St.',
height: '77',
weight: '195',
}
let diff = {}
for (const key in newObject) {
if (previousObject[key] != newObject[key]) {
diff[key] = newObject[key]
}
}
console.log(diff)
I've one object, which I want to be group by based on two keys.
var obj = [{
make: "nissan",
model: "sunny",
colour: "red"
},
{
make: "nissan",
model: "sunny",
colour: "red"
},
{
make: "nissan",
model: "sunny",
colour: "red1"
}];
var result = _.groupBy(obj, p=>p.model);
gives me one result.
I want this to be group Base on model and color, so that I've two results as:
result = [{
make: "nissan",
model: "sunny",
colour: "red"
},
{
make: "nissan",
model: "sunny",
colour: "red"
}];
How I can do this with the help of Underscore js or any other short way.
With underscore.js groupBy you can group multiple properties like this:
const obj = [{make: "nissan",model: "sunny",colour: "red"}, {make: "nissan",model: "sunny",colour: "red"},{make: "nissan",model: "sunny",colour: "red1"}];
const result = _.groupBy(obj, item => item.model + '#' + item.colour);
console.log(result);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
But the result you show in your question looks like you need is Array.prototype.filter():
const obj = [{make: "nissan",model: "sunny",colour: "red"}, {make: "nissan",model: "sunny",colour: "red"},{make: "nissan",model: "sunny",colour: "red1"}];
const result = obj.filter(item => item.model === 'sunny' && item.colour === 'red');
console.log(result);
since you asked "How I can do this with the help of Underscore js or any other short way" , here is a short way using Array.prototype.filter()
var obj = [{
make: "nissan",
model: "sunny",
colour: "red"
},{
make: "nissan",
model: "sunny",
colour: "red"
},
{
make: "nissan",
model: "sunny",
colour: "red1"
}];
var res = obj.filter( key => key.colour === "red")
console.log(res)
var result = _.groupBy(obj, function(o){
return o.model + o.color;
});
I'm tiying to build an excel uploader app. Right now, I can get the data from the excel file and send it to an API to store the info.
But i need something else, and is to asign to each value the id of the excel, which i'll get after save it first.
This is how i get the excel data before store it:
$scope.loadWorksheet = function(e){
var file = e.target.result;
var workbook = XLSX.read(file, { type: "binary" });
var sheetName = workbook.SheetNames[0];
$scope.sheet = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
console.log($scope.sheet);
$scope.$apply();
};
Let's say i get the next array:
[{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}]
How can i add to each record the id of the document?
Per example, after save the document i get on the response the id:
$scope.IdDocument = 15;
And what i need is to put it on every record, like this:
[{Name: "Chuck", Age: "30", DocumentId: "15"},
{Name: "Marcus", Age: "18" DocumentId: "15"},
{Name: "Shelly", Age: "29" DocumentId: "15"}]
There's a way to do that? Hope you can help me.
I'm using AngularJs and Javascript.
You need forEach, with angularjs you can use angular.forEach
DEMO
var array = [{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}];
array.forEach(function(obj) { obj.DocumentId = "15"; });
console.log(array);
Use map function.It will return the updated array
var oldArray = [{
Name: "Chuck",
Age: "30"
},
{
Name: "Marcus",
Age: "18"
},
{
Name: "Shelly",
Age: "29"
}
];
var newArray = oldArray.map(function(item) {
item.DocumentId = '15';
return item;
})
console.log(newArray)
You can just iterate over your array and add the field as follows
var people = [{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}
];
people.forEach(p => p.DocumentId = "15");
console.log(people)
iterate over your array object using for loop
var people = [{Name: "Chuck", Age: "30"},
{Name: "Marcus", Age: "18"},
{Name: "Shelly", Age: "29"}];
for(var i=0 ; i<people.length;i++){
people[i].age = "10";
}
I have the following array.
var gillFamily = [
{ name: 'john', age: 20 },
{ name: 'richard', age: 27 },
{ name: 'debbie', age: 55 },
{ name: 'dan', age: 25 },
{ name: 'robin', age: 60 }
];
I need to print the names with the lastname "Gill" added to them using lodash.
I've tried this which was the closest I got:
_.map(gillFamily, "name") + " Gill";
but that only adds Gill to the last name in the array.
How do I add the name to all items in the array?
One option is:
_.map(gillFamily, (el) => el.name + " Gill");
In case that the environment doesn't support ES6:
_.map(gillFamily, function(el) {
return el.name + " Gill"
});
You could also use Array.prototype.map function.
You need to access the name property inside the Object and then add the Gill string to that name.
var gillFamily = [ {name: 'john', age: 20},
{name: 'richard', age: 27},
{name: 'debbie', age: 55},
{name: 'dan', age :25},
{name: 'robin', age : 60}];
var gillFamilyWithLastNameAdded = _.map(gillFamily, person => person.name + " Gill");
console.log(gillFamilyWithLastNameAdded);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Using the map function you can map each element with the last name appended to using the following. Using _.each(), you can loop over the array of objects and update the property/properties desired. This probably may not be the best/most efficient technique but it's the best I could find by just reading the docs.
Note: This will overwrite the original object.
Disclaimer: I'm not an active lodash user.
// Setup example data
var gillFamily = [{
name: 'john',
age: 20
}, {
name: 'richard',
age: 27
}, {
name: 'debbie',
age: 55
}, {
name: 'dan',
age: 25
}, {
name: 'robin',
age: 60
}];
// Display the initial values
document.getElementById("start").innerText = JSON.stringify(gillFamily);
// Append family name on the current family member's name
var gillFamilyWithLastNames = _.each(gillFamily, function(el) {
// Append 'Gill' to the end of the existing name
el.name += ' Gill';
});
// Show the results
document.getElementById("end").innerText = JSON.stringify(gillFamilyWithLastNames);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<p>Starting Data</p>
<pre id="start"></pre>
<p>Ending Data</p>
<pre id="end"></pre>