Manipulating object properties within an array through iteration

Here is the array I am working with:

var data = [
{"firstname":"A","middlename":"B","lastname":"C"},
{"firstname":"L","middlename":"M","lastname":"N"},
{"firstname":"X","middlename":"Y","lastname":"Z"}
];

I need to update the values for all keys - firstname, middlename, and lastname in this array.

var updatedData = [];
angular.forEach(data, function(item, key) {
    modifiedValues = {};
    angular.forEach(item, function(value, key1) {
          var newValue = value + "constant";
          modifiedValues[key1] = newValue;
    });
    updatedData.push(modifiedValues);    
});

Any assistance on this task would be greatly appreciated. Thank you in advance.

Answer №1

var data = [{
    "name": "John",
    "age": 25,
    "city": "New York"
  },
  {
    "name": "Emily",
    "age": 30,
    "city": "Los Angeles"
  },
  {
    "name": "Michael",
    "age": 22,
    "city": "Chicago"
  }
];
console.log(data.map(obj => {
  return Object.keys(obj).map(key => obj[key] += " added text")
}));

Answer №2

It appears that your goal is to create a map

You may want to consider the following approach:

let data = [
{"first":"John","middle":"Doe","last":"Smith"},
{"first":"Jane","middle":"Marie","last":"Johnson"},
{"first":"Alex","middle":"James","last":"Brown"}
];

let modifiedData = data.map(function(item) {
  return {
     "first" : item.first  + "suffix",
     "middle": item.middle + "suffix",
     "last"  : item.last   + "suffix"
  }
})

Answer №3

One way to transform an array of objects is by using a combination of map() and reduce().

var data = [
  {"name":"John","age":30},
  {"name":"Jane","age":25},
  {"name":"Jake","age":35}
]

var newData = data.map(function(person) {
  return Object.keys(person).reduce(function(obj, key) {
    return obj[key] = person[key] + ' years old', obj
  }, {})
})

console.log(newData)

Answer №4

Iterate through the objects, then update the values of each item:

var data = [{
    "name": "John",
    "age": 30,
    "city": "New York"
  },
  {
    "name": "Alice",
    "age": 25,
    "city": "Los Angeles"
  },
  {
    "name": "Bob",
    "age": 40,
    "city": "Chicago"
  }
];

let newData = data.map(item => {
  let updatedItem = {};
  for (let key in item) {
    if (item.hasOwnProperty(key))
      updatedItem[key] = item[key] + "updated";
  }
  return updatedItem;
});

console.log(newData);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Parcel build was unsuccessful due to an error from @parcel/resolver-default: The file '../../../../../css/main.css' could not be loaded within the './src' directory

I utilize [email protected]. Whenever I attempt to load an external css or javascript file in my index.html, Parcel consistently fails to build with the following error: Build failed. @parcel/core: Failed to resolve './css/main.css' from & ...

Experience the power of CanJS Observable data objects with the added feature of

When working with canJS Observable, I encountered an issue where I cannot use dots in object keys because canJS interprets them as nesting. For example, if I try to create a new observable like this: var obs = new can.Observe( { "div.test-class": { "color ...

Efficiency of Promise-based parallel insert queries in MySQL falls short

I have developed a code in Node.js to execute insert queries using Promise.js but unfortunately, I am encountering an exception stating "Duplicate Primary Key" entry. Here is the snippet of the code: var Promise = require("promise"); var mySql = requir ...

The function save is not available in the Angularjs factory class object

Here is a sample factory class that I am currently working with: angular.module('App') .factory('Session', function($resource) { return { Sessionlogin : function() { return $resource('/api/session/'); }, ...

Angular's directives do not trigger the 'viewContentLoaded' event

I recently created a 'light-gallery' directive that relies on the jquery.lightgallery.js plugin to initialize the $.fn.lightGallery() functions. It is crucial for these functions to be executed after the directive template has been compiled and l ...

Error: The React styleguidist encountered a ReferenceError due to the absence of the defined

After integrating react styleguidist into my project, I encountered an issue when running npm run styleguidist. The error message states: ReferenceError: process is not defined Here is a snippet from my styleguide.config.js file: module.exports = { ti ...

The attribute 'checked' is not a valid property for the 'TElement' type

Learning about typescript is new to me. I have a functional prototype in fiddle, where there are no errors if I use this code. http://jsfiddle.net/61ufvtpj/2/ But in typescript, when I utilize this line - if(this.checked){ it presents an error [ts] Pro ...

Exclusive gathering to discuss @Input attributes

Is there a way to determine if all of the input properties in my component have been initialized with data? Are there any specific events that can help indicate this? Thank you for your assistance! ...

Error: The function callback.apply is not a valid function (Node.js and Mongodb)

Encountered an error when adding the line "{ upsert: true }": Error message: TypeError: callback.apply is not a function // Accessing routes that end in /users/competitorAnalysisTextData // ---------------------------------------------------- router . ...

The next column featuring a dropdown menu

My goal is to make this sketch operational. The red elements in the sketch need to be programmed. Currently, I am using angularJS and bootstrap with the following code: <div class="col-md-6"> <div class="form-group"> <label&g ...

Remove user from axios response interceptor for server-side component

In my Next.js 14 application, I have set up axios interceptors to handle errors. However, I need assistance in logging out the user and redirecting them to the '/login' page if any error occurs. Below is the code snippet for the interceptors: axi ...

What is the reason that JavaScript does not run the code sequentially?

Looking for a solution with a simple function like this: function getArticles(page){ page = page || 1; loading = false; var articlesCache = getArticlesCache(page); if(articlesCache){ articles = articlesCache.data; }else{ make a request a ...

Issues arise when attempting to use two HTTP get requests in a single AngularJS controller

Having two http GET requests in one controller, causing intermittent issues where only one of the GET requests works or sometimes none of them are shown. Any suggestions? }).controller("nextSidorAdminCtrl", function($scope,$rootScope,$http,$location,$s ...

Tips for utilizing multiple ngFor directives for property binding within a single directive

After implementing the ng-drag and drop npm module with the draggable directive, I encountered an issue while trying to display a list of items from a 2D array using li elements. Since multiple ngFor's are not allowed in Angular, I needed to come up w ...

How can I ensure that reactive form fields are properly validated in Angular2?

I am currently facing issues with validating Reactive form field in Angular 2. I have implemented a custom validator for this purpose, but it seems like my approach is not yielding accurate results as some of the test cases are failing. If anyone has insig ...

Converting NumPy arrays to and from a custom C++ Matrix class with the help of pybind11

My current endeavor involves wrapping my C++ code using pybind11. Within the C++ realm, I possess a class called Matrix3D which functions as a 3-D array with dimensions denoted by [n,m,p]. The class operates under the following basic structure: template & ...

On the hunt for a specialized JavaScript library for input validation?

Have you ever come across a JavaScript library that allows for variable validation in a convenient chaining style like this one? For example: if(insertLibraryNameHere(myNumberInput).int().min(0).max(10)) This library also has checks for other data types ...

The function screen.getByText is not available in this context

My experience with jest and react-testing-library has been smooth for the most part, but I encountered some challenges when transitioning to the screen > getByText/etc testing method. Test describe('test the dashboard when loaded', () => { ...

Organizing and arranging elements within an array of arrays in Swift 3

const array = [["Sally", "3", "blue"], ["Jack", "6", "green"], ["Harold", "2", "yellow"]] I'm looking for a solution to sort the elements of this [[String]] by the names listed in the first index (specifically Sally, Jack, Harold). Does anyone know ...

What is the method for breaking a statement within an if statement on Blogger when both the IF and ELSE conditions are met?

I'm making some adjustments to the labels on my blog to ensure that each post has at least two labels. The concept is that if a post has LABEL 1, it will load one script, otherwise it will load another. However, I've encountered a situation wher ...