I am new to angular js, and I was trying to get unique values using ng-repeat. I went through many sites for the example , one of them is enter link description here
which I got from stackoverflow only.
var app = angular.module('app', []);
app.filter('unique', function() {
return function(collection, keyname) {
var output = [],
keys = [];
angular.forEach(collection, function(item) {
var key = item[keyname];
if(keys.indexOf(key) === -1) {
keys.push(key);
output.push(item);
}
});
return output;
};
});
app.controller('MyCtrl', function ($scope) {
$scope.items = [
{ id : 1,column : "col1", comment : "col1-label1",
text1 : "col1-label1-text1",
checked: false,
},
{
id : 2,
column : "col1",
comment : "col1-label2",
text1 : "col1-label2-text1",
checked: false,
},
{
id : 3,
column : "col2",
comment : "col2-label1",
text1 : "col2-label1-text1",
checked: false,
},
{
id : 4,
column : "col2",
comment : "col2-label2",
text1 : "col2-label2-text1",
checked: false,
},
{
id : 5,
column : "col3",
comment : "col3-label1",
text1 : "col3-label1-text1",
checked: false,
},
{
id : 6,
column : "col3",
comment : "col3-label2",
text1 : "col3-label2-text1",
checked: false,
},
{
id : 7,
column : "col4",
comment : "col4-label1",
text1 : "col4-label1-text1",
checked: false,
},
{
id : 8,
column : "col4",
comment : "col4-label2",
text1 : "col4-label2-text1",
checked: false,
}
];
});
But I am having problem to understand at one point that I have spent hours on but still couldn't understand.
**angular.forEach(collection, function(item) {
var key = item[keyname];**
In forEach method in the function we pass value , index and then the object itself that we are iterating over, In the above example we are only passing the value as "item" , then in the next line we are using as object/array. I am really confused, what is it? what are they trrying to do
Related
Some time ago I asked a question about how to filter array based on its key today this function but i am working a new implementation that I'm doing.
create array on basis of object's child
But I'm doing a refactoring of how I treat the field value because before I just need the first object and its value [0].value now I need to expand this logic to work with array I'll leave some examples below.
My Code I'm currently using
https://codesandbox.io/s/lodash-tester-forked-fcdmy1?file=/index.js
Original, unfiltered data from API:
[
{
"_id" : ObjectId("62548802054c225fe560f41a"),
"test" : [
"taetea",
"atty",
],
"Peso" : [
{
"_id" : "624f2ab363dd92f2101de167",
"value" : "255"
}
],
}
]
Expected result for table data:
[
{
"_id" : "62548802054c225fe560f41a",
"test1":"taetea",
"test2":"atty",
"Peso":"255"
},
{
...
},
]
Anyone who can help I'm grateful I will repay with rep+ and my eternal thanks xD
As i understand,you want to use title property from the table Columns & search it in the API data.If the title property represents an array of strings,then add all the strings otherwise add the value property.
const apiData = [
{
"_id" : "62548802054c225fe560f41a",
"test" : [
"taetea",
"atty",
],
"Peso" : [
{
"_id" : "624f2ab363dd92f2101de167",
"value" : "255"
}
],
}
];
const tableData = [
{
title: "Peso",
dataIndex: "peso",
key: "peso",
},
{
title: "test",
children: [
{
title: "ex: ${title} field ${title.length}",
dataIndex: "ex: ${title} + ${title.length}",
key: "ex: ${title} + ${title.length}",
},
{
title: "ex: ${title} field ${title.length}",
dataIndex: "ex: ${title} + ${title.length}",
key: "ex: ${title} + ${title.length}",
},
],
},
];
const tableKeys = tableData.map(t => t.title)
const output = []
apiData.forEach(obj => {
const data = []
Object.keys(obj).filter(key => tableKeys.includes(key)).forEach(key =>{
if(typeof obj[key][0]=== 'string'){
data.push(...obj[key].map((val,index) => ({[`${key}${index+1}`]:val})))
}else{
data.push({[key]: obj[key][0].value})
}
})
// Add the id of the the api data & spread the objects collected
output.push({'_id':obj._id,
...data.reduce((map,elem)=>({...map,...elem}),
{})})
})
console.log('output',output)
I am making query for my orders list, here is the data structure and my database rules:
I use a query like this to find out whether the latest price hit the tp or sl price like this:
function GetBuyList(symbol, currentPrice) {
//Less than or equal to, for buying search tp lesser than current price
var buy_tp = db.ref(`orders/active_orders/${symbol}`).orderByChild("tp").startAt(`buy_tp_${0}`).endAt(`buy_tp_${currentPrice}`)
//More than or equal to, for buying search sl higher than current price
var buy_sl = db.ref(`orders/active_orders/${symbol}`).orderByChild("sl").startAt(`buy_sl_${currentPrice}`).endAt(`buy_sl_${100000000}`)
buy_tp.once("value", function (snapshot) {
// do some stuff once
if (snapshot.val() !== null) {
ProcessOrders(snapshot.val(), 'tpHit', currentPrice)
}
});
buy_sl.once("value", function (snapshot) {
// do some stuff once
if (snapshot.val() !== null) {
ProcessOrders(snapshot.val(), 'slHit', currentPrice)
}
});
}
For price that is in lower value like 1.211, it working fine, but when the price goes larger, the buy_sl query is not working, but the buy_tp query is still working fine. Example, when I query for the price like 34886 for the data below the buy_sl is not working:
Edit:
Hi Frank, herein the json exported:
{
"active_orders" : {
"BTCUSD" : {
"-Masii03kq9LvuLfWOyG" : {
"close_type" : "None",
"lot_size" : 1,
"order_price" : 34888.17,
"sl" : "buy_sl_34887",
"symbol" : "BTCUSD",
"tp" : "buy_tp_34889",
"ts" : 1622301925456,
"type" : "buy",
"uid" : "6XaKYgXCsuMNg1d5bWYHg6ej5sd2"
}
},
"EURUSD" : {
"-MasVPCtD4sdPCcdF9S9" : {
"close_type" : "None",
"lot_size" : 1,
"order_price" : 1.211,
"sl" : "buy_sl_1.210",
"symbol" : "EURUSD",
"tp" : "buy_tp_1.23",
"ts" : 1622298174339,
"type" : "buy",
"uid" : "6XaKYgXCsuMNg1d5bWYHg6ej5sd2"
}
},
"USDJPY" : {
"-MasWoRREHQhvOR6iQ8G" : {
"close_type" : "None",
"lot_size" : 1,
"order_price" : 109.861,
"sl" : "buy_sl_107.0",
"symbol" : "USDJPY",
"tp" : "buy_tp_110",
"ts" : 1622298543910,
"type" : "buy",
"uid" : "6XaKYgXCsuMNg1d5bWYHg6ej5sd2"
}
}
}
}
Example, when I perform the function GetBuyList("EURUSD", 1.3) or GetBuyList("EURUSD", 1.1), the result returned as:
{
'-MasVPCtD4sdPCcdF9S9': {
close_type: 'None',
lot_size: 1,
order_price: 1.211,
sl: 'buy_sl_1.210',
symbol: 'EURUSD',
tp: 'buy_tp_1.23',
ts: 1622298174339,
type: 'buy',
uid: '6XaKYgXCsuMNg1d5bWYHg6ej5sd2'
}
}
When I perform the function like this, GetBuyList("BTCUSD", 34890), it would return:
{
'-Masii03kq9LvuLfWOyG': {
close_type: 'None',
lot_size: 1,
order_price: 34888.17,
sl: 'buy_sl_34887',
symbol: 'BTCUSD',
tp: 'buy_tp_34889',
ts: 1622301925456,
type: 'buy',
uid: '6XaKYgXCsuMNg1d5bWYHg6ej5sd2'
}
}
But when I run this, GetBuyList("BTCUSD", 34886), nothing is return.
sl and tp are both strings and because they are, they won't be parsed as numbers and instead are subject to lexiographic sorting.
One of the most common examples of this happening is if you look at a file list in a folder:
0.jpg
1.jpg
10.jpg
11.jpg
12.jpg
2.jpg
3.jpg
4.jpg
5.jpg
6.jpg
7.jpg
8.jpg
9.jpg
If you can't switch from using strings, you need to pad the number with your expected maximum number:
000.jpg
001.jpg
002.jpg
003.jpg
004.jpg
005.jpg
006.jpg
007.jpg
008.jpg
009.jpg
010.jpg
011.jpg
012.jpg
const formatWithPadding = (inp, digits) => {
let n = Number(inp), nStr = `${Math.abs(n)}`, sign = n<0;
return (sign ? '+' : '-') + (
nStr.length > digits
? nStr
: `${"0".repeat((digits || 1) - 1)}${nStr}`.slice(-digits)
)
};
const tpVal = 1.210;
const [integerPart, fractionalPart] = String(tpVal).split(".");
const tp = `buy_tp_${formatWithPadding(integerPart, 6)}.${fractionalPart || 0}`;
// tp is "buy_tp_+000001.210"
i am trying to check my inner array id same as dispatched id, table example
{
_id :1,
name: sagar elias jacky
Amenities :[{ id: 100, title : hi },{ id: 101, title : hallo } ]
}
checking dispatched id exit or not using map,
return { ...state,
items : {...state.items,
Amenities : { ...state.items.Amenities
.map(x=> x._id === action.dispatchedID ? {...x,deleting: true} : x ) }}}
but it will return with non array Amenities, like
Amenities:
0: { id: 100, title : hi },
1: { id: 101, title : hallo }
i want this to
Amenities:Array(2)
0: { id: 100, title : hi },
1: { id: 101, title : hallo }
When you spread an array inside {}, it creates an object with indexes of array as keys
const array = [{a:1}, {a:2}]
console.log({...array})
So, change
Amenities : { ...state.items.Amenities
.map(x=> x._id === action.dispatchedID ? {...x,deleting: true} : x ) }
to:
Amenities : [ ...state.items.Amenities
.map(x=> x._id === action.dispatchedID ? {...x,deleting: true} : x ) ]
I have an object like this :
Object
section : array (1)
0 : {id : 1, name: 'foo'}
unit : array(2)
0 : {id : 1, name: 'bar'}
1 : {id : 2, name: 'bar2'}
but how to detect if the object has a section key or not ?
my code like this :
$.each(data, function(key,row){
if (row.section) {
$.each(row.section, function(key, val){
$('.select-section').append("<option value='"+val.id+"'>"+val.name+"</option>");
});
}else{
$('.select-section').html("<option value='-'>-</option>");
}
});
but my when i have an object like that above, the results is just replace the section option value with else condition (-)
i create this because sometimes an Object doesn't have a section key, so i create a default option when the section key is unavailable
any help will be appreciated
I changed two things in your JS code:
if (key=="section") instead of if (row.section) to check if the key is section or not;
$('.select-section').append instead of $('.select-section').html cause whatever you could append the html() function will replace the whole html inside the select tag to <option value='-'>-</option>, then you'll never have other option then this one.
Please check this demo for a better understanding:
var object={
section : {
0 : {id : 1, name: 'foo'}
},
unit : {
0 : {id : 1, name: 'bar'},
1 : {id : 2, name: 'bar2'}
}
};
$.each(object, function(key,row){
if (key=="section") {
$.each(row, function(key, val){
var opt="<option value='"+val.id+"'>"+val.name+"</option>";
$(".select-section").append(opt);
});
}else{
$('.select-section').append("<option value='-'>-</option>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select-section"></select>
This solution still not perfect because I believe that if you'll have another key that is not section the code above will append one more the selection tag with -;
var object={
section : {
0 : {id : 1, name: 'foo'}
},
unit : {
0 : {id : 1, name: 'bar'},
1 : {id : 2, name: 'bar2'}
},
unit2 : {
0 : {id : 1, name: 'bar'},
1 : {id : 2, name: 'bar2'}
}
};
$.each(object, function(key,row){
if (key=="section") {
$.each(row, function(key, val){
var opt="<option value='"+val.id+"'>"+val.name+"</option>";
$(".select-section").append(opt);
});
}else{
$('.select-section').append("<option value='-'>-</option>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select-section"></select>
So I suggest that you append the select tag at the beginning, then there is no need to check if the key is not section. Here is another and better demo :
var object={
section : {
0 : {id : 1, name: 'foo'}
},
unit : {
0 : {id : 1, name: 'bar'},
1 : {id : 2, name: 'bar2'}
},
unit2 : {
0 : {id : 1, name: 'bar'},
1 : {id : 2, name: 'bar2'}
}
};
$('.select-section').append("<option value='-'>-</option>");//APPEND It HERE
$.each(object, function(key,row){
if (key=="section") {
$.each(row, function(key, val){
var opt="<option value='"+val.id+"'>"+val.name+"</option>";
$(".select-section").append(opt);
});
}//NO NEED TO CHECK If It's NOT "SECTION"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="select-section"></select>
you can just do:
var data = {
section: [{
id: 1,
name: 'foo'
}],
unit: [{
id: 1,
name: 'bar'
}, {
id: 2,
name: 'bar2'
}]
};
if (data.section && data.section.length > 0) {
$.each(data.section, function(key, val){
$('.select-section').append("<option value='"+val.id+"'>"+val.name+"</option>");
});
} else {
$('.select-section').html("<option value='-'>-</option>");
}
plnkr: http://embed.plnkr.co/dxzbHir4x0RjQwQAfse1/
I have an object which contain name and id. Second object has some fields and that id field from first object.
For Example:
FirstObj = [{
_id: '48765465f42424',
Name : 'Sample'
},{
_id: '48765465f654654',
Name : 'Sample1'
}]
secondObj = [{
Field1 : 5464,
subarray : [{
Field2 : 14654,
Field3 : { IsActive : true,
FirstObjid : '48765465f42424'
},
Field4 : { IsActive : true,
FirstObjid : '48765465f654654'
}
}]
},
{
Field1 : 2145,
subarray : [{
Field2 : 544644,
Field3 : { IsActive : true,
FirstObjid : '48765465f654654'
},
Field4 : { IsActive : true,
FirstObjid : '48765465f42424'
},
}]
}]
Now I need to compare both and push that name from first object to secondobj's subobj beside FirstObjid field .
Expected Output is :
secondObj = [{
Field1 : 5464,
subarray : [{
Field2 : 14654,
Field3 : { IsActive : true,
FirstObjid : '48765465f42424',
Name : 'Sample'
},
Field4 : { IsActive : true,
FirstObjid : '48765465f654654',
Name : 'Sample1'
}
}]
},
{
Field1 : 2145,
subarray : [{
Field2 : 544644,
Field3 : { IsActive : true,
FirstObjid : '48765465f654654',
Name : 'Sample1'
},
Field4 : { IsActive : true,
FirstObjid : '48765465f42424',
Name : 'Sample'
},
}]
}]
How can I achieve it.
Try this
secondObj.subarray.forEach(function(item){
if(item.FirstObjid==FirstObj._id)
item.Name = FirstObj.Name
})
Use map function and compare the object ids like this
var secondObj = [{
Field1 : 5464,
subarray : [{
Field2 : 14654,
Field3 : 'sfsadf',
FirstObjid : '48765465f42424'
}]
},
{
Field1 : 2145,
subarray : [{
Field2 : 544644,
Field3 : 'awrfsa',
FirstObjid : '48765465f654654'
}]
}]
var FirstObj = [{
_id: '48765465f42424',
Name : 'Sample'
},{
_id: '48765465f654654',
Name : 'Sample1'
}]
secondObj.subarray = secondObj.map(o => o.subarray.map(k=> FirstObj.map(l=> {
if(l._id == k.FirstObjid){
k.Name = l.Name
}
return o;
})))
console.log(secondObj)