Iteration over an array of objects - arrays

I have an array of objects from which I intend to copy few of its fields to a different object values on a specific condition
fromPage: "home";
sample = [
{iD:100A,fName:"jack",age:28},
{iD:200A,fName:"kate",age:29},
{iD:300A,fName:"rose",age:30}
]```
` copyObj = [{id:string, name:string}] `
Expecting result:
copyObj = [
{id:100A,name:"jack"},
{id:100B,name:"kate"}
]
I want to copy these specific fields to my copyObj from the sample. I tried in below way but ended up getting undefined.
for(var i=0;i<=sample.length;i++){
if(this.fromPage == "home")
{
this.copyObj[i].id = this.sample[i].iD;
this.copyObj[i].name = this.sample[i].fName;
}
}
The above is throwing error like: cannot read property 'ID' of undefined
Any other way to implement this , please help. I also tried using forEach to iterate and then push the values to the new array but it didn't work.

Try the following code,
this.copyObj=[];
for(var i=0;i<=this.sample.length-1;i++){
if(this.fromPage === "home"){
this.copyObj.push({'id':this.sample[i].iD,'name':this.sample[i].fName});
}
}

Related

Iterating through a JSON array and returning a subset of elements

I'm new to JS and trying to figure out how to iterate through a json array and return only a subset of elements. Specifically I would like to know how to return only the 'first_name' and 'last_name' from the Mock data in the attached code snippet. It seems like it should be straightforward but I'm scratching my head.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
people.forEach(person => {
for (let key in person) {
console.log(`${key} => ${person[key]}`);
}
Use the element names
people.forEach(person => {
console.log(JSON.stringify(person) + "\n");
console.log(person["first_name"], person["last_name"], "\n");
});
Produces this output:
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"}
Talbert Kohnert
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"}
Ruthie McKleod
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
Lenore Foister
You can try Object destructuring assignment of ES6 to achieve the requirement.
Working Demo :
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}];
let res = people.map(({first_name, last_name}) => first_name + ' ' + last_name);
console.log(res);
There are numerous way of achieving this output. One of most frequently used method is using map() of es6.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}]
//by map method
people.map((person,index)=>{
console.log(`${person.first_name} ${person.last_name}`)
})
// by forEach
people.forEach(person => {
console.log(`${person.first_name} ${person.last_name}`)
}
you can achieve this by using the map function.
map lets you iterate over each item in the array and return a new value for each iteration while returning a new array, so for your case:
let people = [
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"tkohnert0#wisc.edu","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"rmckleod1#gizmodo.com","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"lfoister2#epa.gov","country":"Nicaragua"}
]
const newArray = people.map((person) => {
return {
first_name: person.first_name,
last_name: person.last_name
}
})
console.log(newArray)
here you get a new array with just the properties you need.

React : Pushing result of map() to an array

Hello I am trying to map through an array of objects and push them to a new array.
My ISSUE : only the last item of the object is being pushed to the new array
I believe this has to do with React life cycle methods but I don't know where I should I loop and push the values to the array to get the full list
//My object in an array named states
var states = [{"_id":"Virginia","name":"Virginia","abbreviation":"VN","__v":0},{"_id":"North Carolina","name":"North Carolina","abbreviation":"NC","__v":0},{"_id":"California","name":"California","abbreviation":"CA","__v":0}];
export function StateSelect()
{
**EDIT 1**
const options = [];
function getStates()
{
//This is how I am looping through it and adding to an array
{ states.length > 0 &&
states.map(item =>
(
console.log(`ITEM: ${JSON.stringify(item)}`),
options.push([{ value: `${item.name}`, label: `${item.name}`}])
))
}
}
return( {getStates()}: );
}
Thank you
It looks like your getStates() might not even be returning anything... but assuming it is, I believe you should be able to accomplish this using a forEach() fn in order to push values into your options array... Try adding the following into your map:
states.map((item) => {
console.log(`ITEM: ${JSON.stringify(item)}`);
let processed = 0;
item.forEach((i) => {
options.push([{ value: `${i.name}`, label: `${i.name}`}]);
processed++;
if(processed === item.length) {
// callback fn, or return
}
}
.map usually used to return another result, you could just use .forEach
In fact, you don't really need to declare options at all, just use .map on state to return the result would be fine.
return states.length > 0 && states.map(({ name }) => {
return { value: name, label: name };
});

Restangular: Empty array using $object

I display my data in a table (smart-table) and everything is working well but in my angular code, when I try to get my "topicList" it's return an empty array. there is my code and thank you in advance.
$scope.topicList= Restangular.all("topic").getList().$object;
for(var k in $scope.topicList) {
console.log($scope.topicList[k]);
if($scope.topicList[k] === "")
{xxxx}
}
Restangular.all('topic').getList().then(function(response) {
$scope.topicList = response;
...
});
After you've assigned the topicList then you can do your bits and pieces.

How to replace the property of the object dynamically in angualrjs?

var $scope.form = {
Name: "",
fields: []
}
angular.forEach($scope.form.fields, function (f) {
if (f.hasOwnProperty('order')) {
//code to replace the value of the property
} else {
//if order is not present push the new values to the $scope.form.fields.
}
});
I have a pop up their I am appending textboxes.When i append one text box,I am pushing the object to $scope.form.fields i.e.,Name,id,order..When i append the second textbox it is itering 2 times and getting 3 textboxes displayed. Its getting doubled for every new textbox.So I thought when $scope.form.fields contains order i should have a right to change the name of the textbox.If its not present i'l just push those new object into $scope.form.fields.Can anyone give a solution for it .
As I can see you're having an array ie fields and you need to push the new values when array doesn't already contain the same. You can use either indexOf or inArray functions of array. Try below snippet
angular.forEach($scope.form.fields, function (f, key) {
if (f.indexOf('order') >= 0) { // check whether array contains `order` or not
$scope.form.fields[key]['order'] = 'new value';
} else {
$scope.form.fields.push('new value');
}
});

Angularjs: Assigning Array within object

I am having an issue with losing data within an array when i try to assign it to a new array.
My object im using is as follows:
$scope.shops = [
{
name: "Kroger",
items: [ { itemName: "Chips"} ]
}
];
This is the code for the functions im using, it may be a callback issue? or something? Im losing the items info for the shop.
$scope.addItem = function(newItem, newShop){
var x = findShop(newShop);
x.items.push(newItem);
$scope.shops.push(x);
};
findShop = function(shopTag){
var old = angular.copy($scope.shops);
var tar = {
name: shopTag,
items: []
};
$scope.shops = [];
angular.forEach(old, function(shop, key){
if(shop.name === shopTag) {
tar.items = angular.copy(shop.items);
}
else {
$scope.shops.push(shop);
}
});
return tar;
};
the goal is to have the findShop function return a shop with the correct name, with empty items if there wasnt a shop previously, or with items full of the items if the shop was already created. then the addItem will push the item into the shop.items array and push the shop into the $scope
Any help is greatly appreciated!!!
You are right , it is this line which is causing the problem ,
tar.items = shop.items;
Try using it like this ,
tar.items = angular.copy(shop.items);
var old = $scope.shops; // old and $scope.shops point to the same place
..........
$scope.shops = []; // you assigned a new array that overrides the data
............
angular.forEach(old, function(shop, key){ // for each on an empty array????
If you dont want to point to the same reference use:
var copiedObject = angular.copy(objToCopy);
I guess the array is getting empty even before for loop.
Var old is reference to shops array, which you are making empty before foreach.. effectively making old empty...

Resources