Create object using Underscore.js - angularjs

What is the correct Underscore.js way to create a new object called items that consists of each of the item arrays. Where I could then make a POST of each item.name in one call?
var items = [];
item = [{
name: "item1",
desc: "this is a description of item 1",
qty: 1
},{
name: "item2",
desc: "this is a description of item 2",
qty: 5
},{
name: "item3",
desc: "this is a description of item 3",
qty: 3
}];
items.push(item);

If I understand the question correctly you want to convert an array of items to an object where each key is the name of the object
e.g.
{
item1: {
name: "item1",
desc: "this is a description of item 1",
qty: 1
},
item2: { ... },
item3: { ... },
}
If that's the case then you could use the object function that takes two parameters; the first being the list of property names and the second a list of the values:
var items = [{
name: "item1",
desc: "this is a description of item 1",
qty: 1
},{
name: "item2",
desc: "this is a description of item 2",
qty: 5
},{
name: "item3",
desc: "this is a description of item 3",
qty: 3
}
];
var itemsAsAnObject = _.object( _.pluck(items,'name'), items)

Related

change the value of a property inside one object with the value of a property from another object that is inside an array

I have this object
{id: 4450, name: "product name", stock_status: "IN_STOCK", item: 32}
and this array of objects
[{value: "31", label: "1"}, {value: "32", label: "2"}]
Is there a simple way in es6 to match the "item" property from the first object to the "value" property of an object in the array and return the first object with the value of "label" replacing the value of item like this:
{id: 4450, name: "product name", stock_status: "IN_STOCK", item: "2"}
Maybe it will be useful, if you use the spread operator
const obj = {id: 4450, name: "product name", stock_status: "IN_STOCK", item: 32}
const arr = [{value: "31", label: "1"}, {value: "32", label: "2"}]
// arr[i] 'i' is index of object in array
let newObj = { ...obj, item: (arr[1].label)}

Sorting an array of objects alphabetically

I am trying to sort an array of object alphabetically , to make things simple I am using the below example. In my typscript I do splice to insert and remove items from array object.
Array
cars = [{
id: 1,
items: [{
name: 'car1',
description: 'this is car1 description'
},{
name: 'car2',
description: 'this is car2 description'
},{
name: 'car3',
description: 'this is car3 description'
},{
name: 'car4',
description: 'this is car4 description'
},{
name: 'car5',
description: 'this is car5 description'
}]
}];
html
<p-dataView [value]="cars" [paginator]="true" [rows]="5">
<p-header>List of Cars</p-header>
<p-footer>Choose from the list.</p-footer>
<ng-template let-car pTemplate="listItem">
<p-fieldset legend="Header" *ngIf="car.id === 1" [toggleable]="true">
<div *ngFor="let _car of car.items">
{{_car.name}} - {{_car.description}}
</div>
</p-fieldset>
</ng-template>
</p-dataView>
**********************************************UPDATE********************************
Sorry I have one more layer
cars = [{
id: 1,
items: [{
Model:[{
name: 'car1',
description: 'this is car1 description'
}],
Model:[{
name: 'car2',
description: 'this is car2 description'
}],
},
id:2,
items: [{
Model:[{
name: 'car13,
description: 'this is car3 description'
}],
Model:[{
name: 'car4',
description: 'this is car4 description'
}],
}]
}];
I tried
cars[0].items.Model.sort((a,b) => a[0].name > b[0].name ? 1 : -1) //It did not work
also tried
cars[0].items.Model.sort(function (a, b) {
var nameA = a.name.toLowerCase();
var nameB = b.name.toLowerCase();
if (nameA < nameB) //sort string ascending
return -1
})
cars = [{
id: 1,
items: [{
name: 'ab',
description: 'this is car1 description'
},{
name: 'cd',
description: 'this is car2 description'
},{
name: 'car3',
description: 'this is car3 description'
},{
name: 'aaa',
description: 'this is car4 description'
},{
name: 'car5',
description: 'this is car5 description'
}]
}];
cars[0].items.sort((a,b) => a.name > b.name ? 1 : -1)
Or we can simplify to:
cars[0].items.sort((a,b) => a.name.localeCompare(b.name))
I find it most efficient to use a library like Underscore.js for utility functions like this:
Underscore.js and specifically the sortBy method.
Add underscorejs to your project and import it into your component.
import * as _ from 'underscore';
Then call the sort method and pass the array of objects and the key to sort on.
_.sortBy(car.items, 'name');
When you add or remove an item from the car array, resort the car.items collection and reassign it to car
car.items = _.sortBy(car.items, 'name');
Then you can display as you are now, with the sorted data.
naive sort with Array.prototype.sort()
cars.sort(function(x,y) {
if (x.items.name < y.items.name) return -1;
if (x.items.name > y.items.name) return 1;
return 0;
})

How to add values in an array inside an array in AngularJS

I apologize if my title sounds so confusing, as I don't know how to exactly word it. Basically, this is what I'm trying to do.
For example, I have the following array:
var sourceArray = [
{ question: "Question 1", inputType: "radio", answer: "Answer 1", id: "1" },
{ question: "Question 1", inputType: "radio", answer: "Answer 2", id: "2" },
{ question: "Question 1", inputType: "radio", answer: "Answer 3", id: "3" },
{ question: "Question 2", inputType: "radio", answer: "Answer 1", id: "4" },
{ question: "Question 2", inputType: "radio", answer: "Answer 2", id: "5" },
{ question: "Question 2", inputType: "radio", answer: "Answer 3", id: "6" }
]
I want to restructure this so that it'll look like this:
var newArray = [
{
question: "Question 1", inputType: "radio",
choices: [{answer: "Answer 1", id: "1"},
{answer: "Answer 2", id: "2"},
{answer: "Answer 3", id: "3"}
]},
{
question: "Question 2", inputType: "radio",
choices: [{answer: "Answer 1", id: "4"},
{answer: "Answer 2", id: "5"},
{answer: "Answer 3", id: "6"}
]}
]
Answers are grouped by question, so if the next question in the sourceArray is the same with the current, it will push the answers into the choices array.
Is this possible in AngularJS using angular.forEach?
Any help will be appreciated.
Thank you as always for your responses.
Here you go. See the working example below:
// Add a hepler method in the Array to find the value
Array.prototype.find = function(key, value) {
var index = -1;
angular.forEach(this, function(item, i) {
if (item[key] === value) {
index = i;
}
});
return this[index];
};
var app = angular.module("sa", []);
app.controller("FooController", function($scope) {
$scope.sourceArray = [{
question: "Question 1",
inputType: "radio",
answer: "Answer 1",
id: "1"
}, {
question: "Question 1",
inputType: "radio",
answer: "Answer 2",
id: "2"
}, {
question: "Question 1",
inputType: "radio",
answer: "Answer 3",
id: "3"
}, {
question: "Question 2",
inputType: "radio",
answer: "Answer 1",
id: "4"
}, {
question: "Question 2",
inputType: "radio",
answer: "Answer 2",
id: "5"
}, {
question: "Question 2",
inputType: "radio",
answer: "Answer 3",
id: "6"
}];
$scope.newArray = [];
$scope.convert = function() {
// Iterate array
angular.forEach($scope.sourceArray, function(item) {
// Check if the question alrady exists
if (!$scope.newArray.find('question', item.question)) {
// If not, push the question to the array with empty choices
$scope.newArray.push({
question: item.question,
inputType: item.inputType,
choices: []
});
}
var newArrayItem = $scope.newArray.find('question', item.question);
// Push the choices
newArrayItem.choices.push({
answer: item.answer,
id: item.id
});
});
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<div ng-app="sa" ng-controller="FooController">
Before:
<br>{{sourceArray | json}}
<br>
convert
<br>After:
<br>{{newArray | json}}
</div>
You can group together using a for loop,
Here is the code:
function transformArr(orig) {
var newArr = [],
answers = {},
newItem, i, j, cur;
for (i = 0, j = orig.length; i < j; i++) {
cur = orig[i];
if (!(cur.question in answers)) {
answers[cur.question] = {question: cur.question, answers: [],inputType : cur.inputType,id :cur.id};
newArr.push(answers[cur.question]);
}
answers[cur.question].answers.push(cur.answer);
}
return newArr;
}
Working App
You need to filter in the sourceArray, the two Questions List as below:
var question1 = $filter('filter')(sourceArray, {
question: 'Question 1'
});
var question2 = $filter('filter')(sourceArray, {
question: 'Question 2'
});
After that, you should create a new data of array as below:
$scope.questionData = [{
"question": "Question 1",
"inputType": "radio",
"choices": []
}, {
"question": "Question 2",
"inputType": "radio",
"choices": []
}];
Then, you should run loops over the two filtered a variables into the new Array of object:
1):
angular.forEach(question1, function(value, key) {
if (value.question == $scope.questionData[0].question) {
$scope.questionData[0].choices.push({
'answer': value.answer,
'id': value.id
});
}
});
2):
angular.forEach(question2, function(value, key) {
if (value.question == $scope.questionData[1].question) {
$scope.questionData[1].choices.push({
'answer': value.answer,
'id': value.id
});
}
});
Refer here for demo:

Adding JSON Data to an Array in AngularJS

I want to have an Array as below:
$scope.content = { tabs: [{ id: 1, label: "Tab 1" }, { id: 2, label: "Tab 2" }] };
I Receive my data using an ajax request and want to create an object and add it to $scope.content something as below:
var tab = { id: 3, label: "Tab 3" };
$scope.content["tabs"].push(tab);
my result should be as below:
$scope.content = { tabs: [{ id: 1, label: "Tab 1" }, { id: 2, label: "Tab 2" }, { id: 3, label: "Tab 3" }] };
The code you have written should work, but you can access the tabs array directly and just push your new tab object into the array.
$scope.content.tabs.push(tab);

Angular orderBy is not responding

I have an array obj as following:
$scope.list = [
{
_id: "1111",
desc: "Desc 1",
image_url: "uploads/name-1.jpg",
name: "Name 1",
sequence: 0
},
{
_id: "1112",
desc: "Desc 2"
image_url: "uploads/name-2.jpg",
name: "Name 2",
sequence: 2
},
{
_id: "1113",
desc: "Desc 3",
image_url: "uploads/name-3.jpg",
name: "Name 3",
sequence: 3
},
{
_id: "1114",
desc: "Desc 4",
image_url: "uploads/name-4.jpg",
name: "Name 4",
sequence: 4
},
{
_id: "1115",
desc: "Desc 5",
image_url: "uploads/name-5.jpg",
name: "Name 5",
sequence: 0
},
{
_id: "1116",
desc: "Desc 6",
image_url: "uploads/name-6.jpg",
name: "Name 6",
sequence: 0
},
];
and HTML
<span data-ng-repeat="item in list | orderBy: 'sequence' ">{{item.sequence}}</span>
I've also tried orderBy: '-sequence', orderBy: 'sequence':true. orderBy: 'sequence':false. But the order doesn't seem to update!
Can someone please shed some light on this?
Your list is badly defined, as you're missing commas.
The code you posted does work, see here.
<span ng-repeat="item in list | orderBy: 'sequence' ">
{{item.sequence}}
</span>

Resources