Following is the working code - http://plnkr.co/edit/6lRhiTd1BrKRdThY0WNB?p=preview
In this if you select the number from drop down and fill data then click and check console you will see the result like -
[
Object { start_time="12Start", end_time="12END"},
Object { start_time="34start", end_time="786"},
Object { start_time="123", end_time="5656"},
Object { start_time="098", end_time="77"},
Object { start_time="75757", end_time="57567"}
]
Now If you check, there are two arrays - $scope.shiftstart | $scope.shiftend
I am looping through these but one problem with this approach is that-
1) It needs to be dependent on the equal length of arrays.
2) If some one leaves the first end time input field then it comes as undefined in the console.
What I am thinking is to not to use - separate ng-model="shiftstart[shiftnumber]" & ng-model="shiftend[shiftnumber]" instead I could use ONE single array containing multiple objects but I am unable to integrate the solution, let me know what I can amend in my code to make that happen.
Provided I do understand your question correctly, I think you're way overcomplicating stuff. If you simple want to:
a) have a list of shifts, from which one can be selected, and
b) be able to edit that selected shift
then the following is all you need:
ctrl:
$scope.shifts = [
{ nr: 1, start_time: "12Start", end_time: "12END" },
{ nr: 2, start_time: "34start", end_time: "786" },
{ nr: 3, start_time: "123", end_time: "5656" },
{ nr: 4, start_time: "098", end_time: "77" },
{ nr: 5, start_time: "75757", end_time: "57567" }
];
$scope.active = null;
view-demo:
<h3>Select a shift</h3>
<select
data-ng-model="active"
data-ng-options="shift as shift.nr for shift in shifts"
></select>
<div data-ng-show="active">
<h3>Edit start/end</h3>
start time <input data-ng-model="active.start_time"><br>
snd time <input data-ng-model="active.end_time">
</div>
demo: http://jsbin.com/fibilalaciha/1/
Related
This question already has an answer here:
Lodash uniqBy update the latest value
(1 answer)
Closed 9 months ago.
I am working on one project where I need to remove duplicate values from JSON array object with some specification in react JS. I have tried to remove using _.uniqBy but in the output it took very first value from duplicate value which is I don't want.
Suppose You have an array JSON like:
[ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ]
using _.uniqBy I got [ { id: 1, name: 'bob' }, { id: 2, name: 'bill' }] this output.
but I want [ { id: 2, name: 'bill' }, { id: 1, name: 'alice' } ] this output.
As you can see I want output whose name is alice not bob along with id:1.
Can anyone help me?
Thank you.
My first thought is to use a reduce, and shove the items in a map, then get the values:
Object.values(items.reduce((map, item) => ({ ...map, [item.id]: item }), {}))
This is probably not very efficient though if you're dealing with large arrays of have performance concerns.
It's a quick and dirty one-liner. If you want something more efficient I'd take a look at the lodash source code and tweak it to your needs or write something similar:
https://github.com/lodash/lodash/blob/2f79053d7bc7c9c9561a30dda202b3dcd2b72b90/.internal/baseUniq.js
This question already has answers here:
How to sort an array of objects by multiple fields?
(38 answers)
Closed 2 years ago.
I am trying to create 2 sort types in my FE with javascript for my items that come from the backend but I don't know what the logic should look like for it. Where can I read about something like this?
The first way would be to sort them by the date (The most recent first)
The second way would be to sort them by the total number of the awards (Highest number first)
This is how my data looks like:
[
{
awards: {awardOne: 1, awardTwo: 4, awardThree: 8}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
{
awards: {awardOne: 1, awardTwo: 4, awardThree: 8}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
{
awards: {awardOne: 2, awardTwo: 3, awardThree: 2}
createdAt: "2020-11-13T21:12:50.742Z"
text: "Some text"
username: "username"
},
]
Here is an example sorting the data by number of awards in each object: code sandbox. I'm reducing the items in each awards object to a single value and comparing those.
To sort by date, you can use localeCompare like others have pointed out and use a similar pattern.
Update: I just added an working example of sorting by date to the same sandbox
I am thinking you can sort the items by date lexiographically.
Using String.prototype.localeCompare your code would something like
data.sort((a, b) => {
return ('' + a.createdAt).localeCompare(b.createdAt);
}
Source
To sort by number of awards you would need a smaller function, that calculates number of awards, and then write something like:
data.sort((a, b) => {
return (calcNumOfAwards(a) - calcNumOfAwards(b))
}
Is it possible to use a JavaScript object as a type of mini database? I often find myself needing a kind of database structure when I'm coding in JS but it feels like overkill to use an actual database like MySQL (or similar).
As an example, let's say I need to structure this data as a JS object:
Object idea: Stuff to sell
Items to sell: The junk in the garage
Object structure: List all items including item name, item condition, and item value
In order to make this into a JS object I would maybe write:
var stuffToSell = {};
Then my first item would maybe look like:
var stuffToSell = {
item : "Coffee Maker",
condition : "Good",
price : 5
};
Now to me this seems like I'm on the right track, until I come to add another item and I end up having to use the properties item, condition, and price again in the same JS object — which feels wrong? — or is it?? At this point my brain keeps shouting the word "ARRAY!" at me but I just can't see how I can use an array inside the object, or an object inside an array to achieve what I want.
My end goal (in this simplified example) is to be able to then use object-oriented syntax to be able to access certain items and find out specific information about the item such as price, condition etc. For example if I want to know the price of the "coffee maker" I would like to write something like:
stuffToSell["coffee maker"].price
...and then the result above should be 5.
I feel like I'm on the right track but I think I'm missing the array part? Could someone please tell me what I'm missing or maybe what I'm doing completely wrong! And also if it is wrong to have duplicate property names in the same JS object? For example, is it okay to have:
var stuffToSell = {
item : "Coffee Maker",
price : 5,
item : "Mountain Bike",
price : 10,
item : "26 inch TV",
price : 15
};
...it seems wrong because then how does JS know which price goes with which item??
Thanks in advance :)
You're definitely on the right track!
A lot of people will refer to what you're talking about as a hash.
Here's my suggested structure for you:
var store = {
coffee_maker: {
id: 'coffee_maker',
description: "The last coffee maker you'll ever need!",
price: 5,
},
mountain_bike: {
id: 'mountain_bike',
description: 'The fastest mountain bike around!',
price: 10,
},
tv: {
id: 'tv',
description: 'A big 26 inch TV',
price: 15,
},
}
Having a structure like that will let you do this:
store.mountain_bike.price // gives me 10
Need an array instead, say for filtering or looping over?
Object.keys gives you an Array of all the object's keys in the store ['coffee_maker', 'mountain_bike', 'tv']
// Now we just have an array of objects
// [{id: 'coffee_maker', price: 5}, {id: 'mountain_bike', price: 10} ...etc]
var arr = Object.keys(store).map(el => store[el])
Need to just filter for items that are less than 10?
This will give us an array of products less than 10:
// gives us [{id: 'coffee_maker', price: 5}]
var productsUnder10 = arr.filter(el => el.price < 10)
These techniques can be chained:
var productsOver10 = Object.keys(store)
.map(el => store[el])
.filter(el => el.price > 10)
Need to add a product?
store['new_product'] = {
id: 'new_product',
description: 'The Newest Product',
price: 9000,
}
Here's another way, which would be good to start getting used to.
This is a 'safe' way to update the store, read up on immutability in javascript to learn about it
store = Object.assign({}, store, {
'new_product': {
id: 'new_product',
description: 'The Newest Product',
price: 9000,
}
})
...and another way, that you should also read up on and start using:
This is the object spread operator, basically just an easier way to work with immutable structures
store = {
...store,
'new_product': {
id: 'new_product',
description: 'The Newest Product',
price: 9000,
}
}
Resources
JavaScript Arrow Functions
Object and Array Spread Syntax
Immutable Javascript using ES6 and beyond
You can actually use json or create an array of objects.If using a separate file to store the objects, first load the file. Use array filter method to get an new array which matches the filter condition , like you want to get the item with id 1. This will return an array of objects.
var dict = [{
'id': 1,
'name': 'coffee-mug',
'price': 60
},
{
'id': 2,
'name': 'pen',
'price': 2
}
]
function getItemPrice(itemId) {
var getItem = dict.filter(function(item) {
return item.id === itemId
});
return getItem[0].price;
}
console.log(getItemPrice(1))
JSON objects don't support repeated keys, so you need to set unique keys.
Put an id as your key to group your items:
var stuffToSell = {
'1': {
item: "Coffee Maker",
price: 5
},
'2': {
item: "Mountain Bike",
price: 10
}
.
.
.
}
Now you can access the item's price very fast.
Look at this code snippet (Known Ids)
var stuffToSell = {
'1': {
item: "Coffee Maker",
price: 5
},
'2': {
item: "Mountain Bike",
price: 10
},
'3': {
item: "26 inch TV",
price: 15
}
};
let getPrice = (id) => stuffToSell[id].price;
console.log(getPrice('1'));
See? the access to your items it's fast and your code follows a readable structure.
Look at this code snippet (Item's name as key)
var stuffToSell = {
'Coffee Maker': {
price: 5
},
'Mountain Bike': {
price: 10
},
'26 inch TV': {
price: 15
}
};
let getPrice = (id) => stuffToSell[id].price;
console.log(getPrice('Coffee Maker'));
Look at this code snippet (Item's name: price)
var stuffToSell = {
'Coffee Maker': 5,
'Mountain Bike': 10,
'26 inch TV': 15
};
let getPrice = (id) => stuffToSell[id];
console.log(getPrice('Coffee Maker'));
So I am trying to combine 2 different javascript object than I can end up using in an angularjs ng-repeat . since there is a 1 to many relationship from the database, I was pulling queries separately.
What I have is this:
Main list of data , 3 object sample
0: Object
$$hashKey: "object:4"
Active:true
QuestionId:2
SalesChannel:"DTD"
1: Object
$$hashKey: "object:5"
Active:true
QuestionId:3
SalesChannel:"DTD"
2: Object
$$hashKey: "object:6"
Active:true
QuestionId:5
SalesChannel:"DTD"
Then another query returned data into what I want to relate as JSON into the other object
Object { Id: 3, Name: "Text box" QuestionId: 3}
{ Id: 4, Name: "Text box" QuestionId: 3}
{ Id: 9, Name: "Text box" QuestionId: 5}
So since I have both of these objects , I am wanting to combine.
Naturally I would think that I should return from the database, but then I also think about looping over and appending
for loop on main
{
.... find where main.QuestionId = sub.QuestionId and it to be added in as a nested object of json type...
Thus the end result SHOULD look like
[{
Active:true,
QuestionId: 3
SubData: [ {
Id: 3,
Name: "TextBox
QuestionId:3
},
{
Id: 4,
Name: "TextBox
QuestionId:3
}],
SalesChannel: "DTD"
}]
// and so on
How can i achieve this?
You want to go through all of the main objects, and assign to them only those results from second query. Use Array.prototype.forEach to go through them all, and Array.prototype.filter to select only appropriate results from secondary query.
firstQueryResult.forEach((firstObject)=>
firstObject.subdata = secondQueryResult.filter((secondObject)=>
secondObject.QuestionId === firstObject.QuestionId))
BTW, this has nothing to do with angularjs
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
I have a problem here, and I can't find out how to solve it. I have an object with many levels. There is arrays with objects inside my object, and they have their arrays with objects too. Let me show you somekind of example here:
{
sections: [
{
currency_sections: [
{
positions: [
{
id: 131,
quantity: 24
},
{
id: 133,
quantity: 1
}
],
key: value,
key: value
},
{
positions: [
{
id: 136,
quantity: 2
},
{
id: 137,
quantity: 3
}
],
key: value,
key: value
}
],
key: value,
key: value
}
],
key: value,
key: value
}
I build my data via handlebars template. Which is not really important. But on my page I can change, let's say, quantity of the position. When I do that I have only id of the position I changed and new quantity.
So basically I need to filter my object to find one object in positions arrays that matches via id key and change quantity there.
Also I can delete whole position, and in that case I need to find position object with id needed and delete whole object.
The thing I can't understand is how I can filter all my data at once. And how can I manipulate unnamed object if I will find it.
And let's say I filtered it somehow. Can I return full path to that object for later use? In example - sections[0].currency_sections[1].positions[0] ? Because if I can do that than deleting and editing should be simple enough.
At this point I don't really have the time to redo everything on something more suitable like angular or ember. Although I have underscore and jquery.
Just wanted to update my question. At the end I just created a method that builds index of my elements.
function _createItemsIndex(data) {
if (!$.isEmptyObject(data)) {
$.each(data.sections, function (sectionIndex, section) {
$.each(section.currency_sections, function (curSecIndex, curSec) {
$.each(curSec.positions, function (positionIndex, position) {
_items.push({
id: position.id,
quantity: position.quantity,
price: parseFloat(position.price) || 0,
index: [sectionIndex, curSecIndex, positionIndex]
});
});
});
});
}
}
Thank you levi for your comments