Order by Object key in ng-repeat - angularjs

How can I order by key as integer?
I have the following Object;
$scope.data = {
"0": { data: "ZERO" },
"1": { data: "ONE" },
"2": { data: "TWO" },
"3": { data: "TREE" },
"5": { data: "FIVE" },
"6": { data: "SIX" },
"10":{ data: "TEN" },
"11": { data: "ELEVEN" },
"12": { data: "TWELVE" },
"13": { data: "THIRTEEN" },
"20": { data: "TWENTY"}
}
HTML:
<div ng-repeat="(key,value) in data">
The current output order is 1,10,11,12,13,14,2,20,3,4,5,6
But I want 1,2,3,4,5,6,10,11,12,13,14,20
| orderBy:key
don't work for me.
Any ideas?
Thanks!

An option would be use an intermediate filter.
PLUNK AND Code Snippet
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.template = {
"0": { data: "ZERO" },
"1": { data: "ONE" },
"2": { data: "TWO" },
"3": { data: "TREE" },
"5": { data: "FIVE" },
"6": { data: "SIX" },
"10":{ data: "TEN" },
"11": { data: "ELEVEN" },
"12": { data: "TWELVE" },
"13": { data: "THIRTEEN" },
"20": { data: "TWENTY"}
}
});
app.filter('toArray', function() { return function(obj) {
if (!(obj instanceof Object)) return obj;
return _.map(obj, function(val, key) {
return Object.defineProperty(val, '$key', {__proto__: null, value: key});
});
}});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore.js"></script>
<body ng-app="app" ng-controller="MainCtrl">
<div ng-repeat="(key, value) in template| toArray | orderBy:key">{{key}} : {{value.$key}} : {{value.data}}</div>
<body>
NOTE:
The above filter requires Underscore.js, if you don't use it, can rewrite the filter.

I think it sorts itself out with a conversion to an array. pun intended.
var obj = {"3": {three:3}, 2: {two:2}, "5": {five:5}, 4: {four:4},
1: {one:1}, 6: {six:6}, 10: {ten:10}, 11:{eleven:11}
}
$scope.arr = [];
for (var o in obj)
$scope.arr.push(obj[o])

app.filter('orderObjectBy', [function() {
return (filterObj, prop) => {
let arr = []
//below is the loadash function you can use for in also
_.forEach(filterObj, function(value, key) {
arr.push({
key: key,
value: value
});
});
let sortedArr = _.sortBy(arr, val => val.value[prop]);
for (let variableKey in filterObj) {
if (filterObj.hasOwnProperty(variableKey)) {
delete filterObj[variableKey];
}
}
for (let data of sortedArr) {
filterObj[data.key] = data.value;
}
return filterObj;
}
}])

Related

How to get the minimum value by react js

In the code below, I am trying to run {this.renderCost(data,'mina')} with react js. I would like to obtain the minimum value of total using the code below, but total of an object that value of nameis Equal to for example mina(or other name because it will be changed).
I tried the following :
Firstly push the value of total using indents.push(elem.total), the expected output for this part is [2000,1000] and then get minimum value of array by Math.min(...indents),the expected output for this part is [1000] but the function doesn't work.
const data = [
{
"obj": {
"no": "1",
"info": [
{
"name": "maya"
},
{
"name": "mina"
}
],
"total":"2000"
}
},
{
"obj": {
"no": "2",
"info": [
{
"name": "maya"
}
],
"total":"1000"
}
},
{
"obj": {
"no": "3",
"info": [
{
"name": "mina"
},
{
"name": "Mike"
}
],
"total":"1000"
}
}
]
renderCost(data,name){
let indents = [];
data.map((elem) => {
this.renderTotal(elem,name,indents)
})
}
renderTotal(elem,name,indents){
for(let i = 0 ; i < elem.info.length;i++){
if (elem.info[i].name == name){
indents.push(elem.total)
}
return (
Math.min(...indents)
)
}
}
The data structure you're working with isn't ideal for this particular search however you can get to your answer with the following:
const minTotalByName = (data, name) => {
const totals = data
.filter(x =>
x.obj.info.find(y => y.name === name)
).map(x => x.obj.total);
return Math.min(...totals);
}
const min = minTotalByName(data, "mina"); // 1000
To find the min value for the name you can use below code:
const { useState } = React;
function App() {
const [name, setName] = useState("");
const filtered = data
.filter(obj => obj.obj.info.some(n => n.name === name))
.map(obj => Number(obj.obj.total));
const min = filtered.length !== 0 ? Math.min(...filtered) : "";
return (
<div>
<input onChange={(e) => setName(e.target.value)} />
<div>The result is: {min}</div>
</div>
);
}
const data = [
{
obj: {
no: "1",
info: [ { name: "maya" }, { name: "mina" } ],
total: "2000"
}
},
{
obj: {
no: "2",
info: [ { name: "maya" } ],
total: "1000"
}
},
{
obj: {
no: "3",
info: [ { name: "maya" }, { name: "Mike" } ],
total: "1000"
}
}
];
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Issues with transforming array data

I'm trying to transform the following JSON array data structure -
From
[
{
"date": "2019-01-01",
"marks": [
{
"quantity": {
"shoes": 1,
"belt": 2,
"socks": 3
}
}
]
},
{
"date": "2019-01-02",
"marks": [
{
"quantity": {
"shoes": 4,
"belt": 5,
"socks": 6
}
}
]
}
]
To
rows: [
{
values: [ '2019-01-01', 1, 2, 3]
},
{
values: [ '2019-01-02', 4, 5, 6]
}
]
The code that I was able to try so far is this -
function myFunction() {
var response = [
{
"date": "2019-01-01",
"marks": [
{
"quantity": {
"shoes": 1,
"belt": 2,
"socks": 3
}
}
]
},
{
"date": "2019-01-02",
"marks": [
{
"quantity": {
"shoes": 4,
"belt": 5,
"socks": 6
}
}
]
}
];
var transform = response.map(function(dailyMarks) {
var row = [];
Object.keys(response).asArray().forEach(function (field) {
switch (field) {
case 'shoes':
return row.push(dailyMarks.shoes);
case 'belt':
return row.push(dailyMarks.belt);
case 'socks':
return row.push(dailyMarks.socks);
case 'date':
return row.push(dailyMarks.date);
default:
return row.push('');
}
});
return { values: row };
});
Logger.log(transform);
}
However, I'm running into this error -
TypeError: Cannot find function asArray in object 1,2. (line XX, file "Code")
Pretty sure I'm doing something wrong but have not been able to figure out where.
Objective is simply to transform the aforementioned data structure - approach doesn't really matter.
Any help would be highly appreciated! Thanks.
In ES5,
var arr1 = [
{
date: '2019-01-01',
marks: [
{
quantity: {
shoes: 1,
belt: 2,
socks: 3,
},
},
],
},
{
date: '2019-01-02',
marks: [
{
quantity: {
shoes: 4,
belt: 5,
socks: 6,
},
},
],
},
];
var out = [];
arr1.forEach(function(obj) {
obj.marks.forEach(function(mark) {
out.push({
values: [obj.date].concat(
Object.keys(mark.quantity).map(function(key) {
return mark.quantity[key];
})
),
});
});
});
console.log({ rows: out });
You could take an array of keys for the order and flatmap the marks array.
var data = [{ date: "2019-01-01", marks: [{ quantity: { shoes: 1, belt: 2, socks: 3 } }] }, { date: "2019-01-02", marks: [{ quantity: { shoes: 4, belt: 5, socks: 6 } }] }],
keys = ['shoes', 'belt', 'socks'],
rows = data.map(({ date, marks }) =>
({ values: [date, ...marks.flatMap(({ quantity }) => keys.map(k => quantity[k]))] })),
result = { rows };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
let x = products.map(p=>{
return p.marks.reduce((t,m)=>{
t.push({ values: [p.date, ...Object.entries(m.quantity).map(([key, value]) => value)]})
return t;
},[])
}
).flat(2)
console.log(x)
var list=[{"date":"2019-01-01","marks":[{"quantity":{"shoes":1,"belt":2,"socks":3}}]},{"date":"2019-01-02","marks":[{"quantity":{"shoes":4,"belt":5,"socks":6}}]}];
let result = list.map(( {date, marks} ) => { return {value: [date, ...Object.values(marks[0].quantity)]};});
let wrap = {rows: result};
console.log(wrap);

Angularjs Splice in Nested Array

Hi can somebody help Removing element from nested json array like this
JSON
[{
"id": 1,
"name": "Furniture & Fixture",
"choice": {
"0": {
"req_goods": "table",
"qty": "10"
},
"1": {
"req_goods": "chair",
"qty": "5"
}
}
}, {
"id": 2,
"name": "Miscellaneous Property",
"choice": {
"0": {
"req_goods": "Office Rent",
"qty": "1"
}
}
}]
here how do I remove choice 1 of id 1 .
HTML
<div ng-repeat="cb in capital_budgets">
<div ng-repeat="choice in choices[$index]">
<input ng-model="cb.choice[$index].req_goods">
<input ng-model="cb.choice[$index].qty">
<button ng-hide="$first" ng-click="removeChoice($parent.$index,$index)">-</button>
</div>
<button ng-click="addNewChoice($index)">+</button>
</div>
JS
$scope.capital_budgets = [{"id":1,"name":"Furniture & Fixture"},
{"id":2,"name":"Miscellaneous Property"}];
$scope.choices = [{}];
$scope.choices[0] = [{}];
$scope.choices[1] = [{}];
$scope.choices[2] = [{}];
$scope.choices[3] = [{}];
$scope.choices[4] = [{}];
$scope.addNewChoice = function(id) {
$scope.choices[id].push({});
};
$scope.removeChoice = function(parent_id, id) {
$scope.choices[parent_id].splice(id, 1);
};
The Above removeChoice() remove last element but I want to remove the element that user choose to remove. please help i have been trying from 2 days.
You can make 'choice' of the array type as follows and use the index of the particular choice in the ng-repeat directive to remove the choice from the choices array.
angular
.module('demo', [])
.controller('DefaultController', DefaultController);
function DefaultController() {
var vm = this;
vm.items = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
vm.removeChoice = removeChoice;
vm.addChoice = addChoice;
function removeChoice(itemId, index) {
for (var i = 0; i < vm.items.length; i++) {
if (vm.items[i].id === itemId) {
vm.items[i].choices.splice(index, 1);
break;
}
}
}
function addChoice(index) {
var id = vm.items[index].choices.length + 1;
vm.items[index].choices.push({
id: id,
req_goods: "",
qty: 0
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
<div ng-controller="DefaultController as ctrl">
<div ng-repeat="item in ctrl.items">
<h3>{{item.name}}</h3>
<div ng-repeat="choice in item.choices">
<input type="text" ng-model="choice.req_goods" />
<input type="text" ng-model="choice.qty" />
<button type="button" ng-click="ctrl.removeChoice(item.id, $index)">Remove</button>
</div>
<button type="button" ng-click="ctrl.addChoice($index)">Add</button>
</div>
</div>
</div>
You can remove choice "1" of id 1 using the below code snippet.
var json = [
{
"id": 1,
"name": "Furniture & Fixture",
"choice": {
"0": {
"req_goods": "table",
"qty": "10"
},
"1": {
"req_goods": "chair",
"qty": "5"
}
}
}, {
"id": 2,
"name": "Miscellaneous Property",
"choice": {
"0": {
"req_goods": "Office Rent",
"qty": "1"
}
}
}];
function removeChoice(json, parentId, choice) {
for (var i = 0; i < json.length; i++) {
if (json[i].id === parentId) {
delete json[i].choice[choice];
break;
}
}
}
removeChoice(json, 1, "1");
console.log(json);
If you want the the choice also to be of the same type as its parent element i.e. an array you could change your JSON as follows and do as shown in the below code snippet to remove a choice from the JSON
var json = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
function removeChoice(json, parentId, choiceId) {
for (var i = 0; i < json.length; i++) {
if (json[i].id === parentId) {
for (var j = 0; j < json[i].choices.length; j++) {
if (json[i].choices[j].id === choiceId) {
json[i].choices.splice(j, 1);
break;
}
}
break;
}
}
}
removeChoice(json, 1, 1);
console.log(json);
In both of the above methods I've passed the source you want to modify as a parameter to the removeChoice function whereas you can also directly use a variable available within the scope of execution of the removeChoice function and pass only parentId and choiceId as parameters in the below code snippet, you can replace items with the object on your controller's $scope.If you prefer isolation of the code you can pass the items object as a parameter to the removeChoice function as it won't be dependent on the external components directly being used in the method body, I would suggest to have separation of concerns.
var items = [
{
"id": 1,
"name": "Furniture & Fixture",
"choices": [
{
"id": 1,
"req_goods": "table",
"qty": "10"
},
{
"id": 2,
"req_goods": "chair",
"qty": "5"
}]
}, {
"id": 2,
"name": "Miscellaneous Property",
"choices": [
{
"id": 1,
"req_goods": "Office Rent",
"qty": "1"
}]
}];
function removeChoice(parentId, choiceId) {
for (var i = 0; i < items.length; i++) {
if (items[i].id === parentId) {
for (var j = 0; j < items[i].choices.length; j++) {
if (items[i].choices[j].id === choiceId) {
items[i].choices.splice(j, 1);
break;
}
}
break;
}
}
}
removeChoice(1, 1);
console.log(items);
Try This
$scope.removeChoice = function(parent_id,id) {
var TempArr=[];
var parentLength=$scope.choices[parent_id].length;
for(i=0;i<parentLength;i++ ){
if(parentLength[i]!==id){
TempArr.push(parentLength[i]);
}
if(i==parentLength-1){
$scope.choices[parent_id]=[];
$scope.choices[parent_id]=TempArr;
}
}
};

How to map json data with array in react native

I have array like this in react native
const data = [
{ key: 1, label: 'Service1'},
{ key: 2, label: 'Service2' },
{ key: 3, label: 'Service3' },
{ key: 4, label: 'Service4' },
{ key: 5, label: 'Service4' },
];
and json data:
"services": [
{
"id": 1,
"name": "Hotels",
},
{
"id": 2,
"name": "Embassies",
},
]
How to map id to key and name to label???
You want to fill your const data with values from JSON, correct?
Try this:
var jsonData = {
"services": [
{ "id": 1, "name": "Hotels" },
{ "id": 2, "name": "Embassies" }
]
};
var data = jsonData.services.map(function(item) {
return {
key: item.id,
label: item.name
};
});
console.log(data);
if your data like below (removed services key)
var jsonData = [
{ "id": 1, "name": "Hotels" },
{ "id": 2, "name": "Embassies" }
];
var data = jsonData.map(function(item) {
return {
key: item.id,
label: item.name
};
});
console.log(data);
i know it to much late,but i hope its helpfull for others,How to fetch the response of JSON array in react native?How to map json data with array in react native
export default class ExpenseNew extends Component {
constructor(){
super();
this.state={
PickerSelectedVal : '',
accountnameMain:[],
}
}
componentDidMount(){
var account_nam=[]
fetch('your Url', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + your token }
})
.then((response) => response.json())
.then((customerselect) => {
// alert(JSON.stringify(customerselect))
global.customerdata = JSON.stringify(customerselect)
var customername = JSON.parse(customerdata);
//alert(JSON.stringify(customername));
for (i = 0; i < customername.cus_data.length; i++) {
var dataa = customername.cus_data[i]["account_name"];
account_nam.push(dataa)
}
this.setState({accountnameMain:account_nam});
})
.done();
}
render() {
return (
<Picker
selectedValue={this.state.PickerSelectedVal}
placeholder="Select your customer"
mode="dropdown"
iosIcon={<Icon name="arrow-down" />}
onValueChange={(itemValue, itemIndex) => this.setState({PickerSelectedVal: itemValue})} >
{this.state.accountnameMain.map((item, key)=>(
<Picker.Item label={item} value={item} key={key}/>)
)}
</Picker>
)
}
}
the above example is fetch array of data from json,and map data in to dropdown/picker,i hope its helpfull for others,if you have any query, asked from me

How to push named Json Array Into Json Object

I want to push below data. I want order the items, it consists of following fields:
var OrderItem = {"itemid":item.itemid,"itemname":item.itemname,"qty":1,"itemprice":item.itemprice};
But I want to Store Like this
{
"Items": [
{
"itemid": 50,
"itemname": "sample",
"itemprice": 124,
"qty": 1
},
{
"itemid": 52,
"itemname": "sample",
"itemprice": 124,
"qty": 1
}
]
}
Controllers:
$scope.addnew=function(item){
var OrderItem= {"itemid":item.itemid,"itemname":item.itemname,"qty":1,"itemprice":item.itemprice};
NewOrderService.addOrderitems(OrderItem);
}
}
Services:
servctrl.service("NewOrderService", function(NewOrderFactory) {
this.addOrderitems = function(orderitemnew) {
NewOrderFactory.AddOrdernew(orderitemnew);
}
});
Factorys:
factmodule.factory("NewOrderFactory",function(){
var orderitemsnew=[];
return {
AddOrdernew:function(orderitemnew){
orderitemsnew.push(orderitemnew);
}
}
});
How to Achieve this?
probably like this?
factmodule.factory("NewOrderFactory",function(){
var orderitemsnew={
items = [];
};
return{
AddOrdernew:function(orderitemnew){
orderitemsnew.items.push(orderitemnew);
},
getOrderItemsNewList: function() {
return orderitemsnew;
}
};
});

Resources