Steps for inserting a key value pair into an object

I am working with a Datasource that contains a nested array of objects. I successfully selected key value pairs, and now my goal is to add those values to the top level of the object, outside of the nested object.

Here is the original array:

 data= [
  {
    "flowId": 7079,
    "flowName": "jackson-demo",
    "version": 1,
    "CreatedDate": "2020-04-02",
    "UpdateDate": "",
    "LastRunDate": "2020-04-02",
    "active": false,

"properties": [
  {
    "id": 7080,
    "key": "country",
    "value": "in",
    "category": "General"
  },
  {
    "id": 7081,
    "key": "source",
    "value": "hive",
    "category": "General"
  }
  ]

  },
  {

"flowId": 7079,
"flowName": "jackson-demo",
"version": 1,
"CreatedDate": "2020-04-02",
"UpdateDate": "",
"LastRunDate": "2020-04-02",
"active": false,

"properties": [
  {
    "id": 7080,
    "key": "country",
    "value": "au",
    "category": "General"
  },
  {
    "id": 7081,
    "key": "source",
    "value": "aws",
    "category": "General"
  }
  ]

} ]

The code snippet below allows me to extract the key value pairs:

 for (var i = 0; i < data.length; i++) {
  data[i].properties.forEach((arrayItem, i) => {
    if (arrayItem.key === 'country') {
      console.log('Key: ' + arrayItem.key + ' ' + 'Value: ' + arrayItem.value);
    }
  });
}

Output generated by the code:

Key: country Value: au 
Key: country Value: in 

My question now is, how can I insert these extracted values back into the array to achieve the following structure:

data= [
  {
    "flowId": 7079,
    "flowName": "jackson-demo",
    "version": 1,
    "CreatedDate": "2020-04-02",
    "UpdateDate": "",
    "LastRunDate": "2020-04-02",
    "active": false,
    "country": "in"

"properties": [
  {
    "id": 7080,
    "key": "country",
    "value": "in",
    "category": "General"
  },
  {
    "id": 7081,
    "key": "source",
    "value": "hive",
    "category": "General"
  }
  ]

  },
  {

"flowId": 7079,
"flowName": "jackson-demo",
"version": 1,
"CreatedDate": "2020-04-02",
"UpdateDate": "",
"LastRunDate": "2020-04-02",
"active": false,
"country":"au"

"properties": [
  {
    "id": 7080,
    "key": "country",
    "value": "au",
    "category": "General"
  },
  {
    "id": 7081,
    "key": "source",
    "value": "aws",
    "category": "General"
  }
  ]

} ]

Answer №1

Attempt to refresh data[i] by utilizing the spread operator :

 for (var i = 0; i < data.length; i++) {
  data[i].properties.forEach((arrayItem, i) => {
    if (arrayItem.key === 'country') {
      data[i] = { ...data[i] , arrayItem }
    }
  });
}

Answer №2

An alternative approach is to utilize the Object.fromEntries method:

for (let entry of data) {
  Object.assign(entry,
    Object.fromEntries(entry.attributes.map(({name, val}) => [name, val]))
  );
}

If you only need to include specific pairs or if you just need one value (e.g., "country"), you can either filter the result of .map or use a simpler programming pattern:

for (let entry of data) {
  entry.country = entry.attributes.find(({name}) => name == "country").val;
}

Answer №3

Transforming the array by adding a new country property to each object:

const addCountryProperty = rawData => rawData .map (({info, ...restData}) => {
  const countryInfo = info .find (({key}) => key == 'country')
  return {
    ... restData,
    ... (countryInfo ? {country: countryInfo .value} : {}),
    info
  }
})

const rawData = [{id: 1234, name: "example1", country: "US"}, {id: 5678, name: "example2", country: "CA"}];

console .log (
  addCountryProperty (rawData)
)
.as-console-wrapper {min-height: 100% !important; top: 0}

If the inclusion of info in the output is redundant post-extraction, it can be omitted for streamlined processing.

We could potentially modify the original data directly, but let's maintain some decency, shall we?

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

Angular - ng-class - dynamic progress tracker

I am currently developing a multi-step wizard in AngularJS that consists of three states. Each state should correspond to specific steps being active in the wizard. I have attempted to achieve this by assigning a class of 'active' to each step ba ...

A step-by-step guide for setting up MongoDB on a "Blank Node.js Console Application" project in VS2015 with TypeScript

Here is my process: First, I installed MongoDB Next, I opened Visual Studio 2015 Then, I created a new project by going to "File" -> "New" -> "Project" -> "TypeScript" -> "Blank Node.js Console Application" After that, I opened the project fo ...

Duplicate values of React object properties when using .push method within a loop

In my code, I've implemented a function called handleCreate that is responsible for taking user data and inserting it into a database. Within the loop of aliasArr.forEach(), I am sending new user instances to my database for each element in the alias ...

Troubleshooting: AngularJS fails to refresh UI when using SignalR

When I attempt to incorporate this angularjs code into a signalR function, the UI does not update. Even using $scope.$apply() does not trigger a digest. This is the code snippet: var notificationHub = $.connection.progressNotificationHub; notificationHub. ...

Converting the Angular 6 HTTP.get response to a string

When I call the GetServiceProviderId() function in my code, I am making a GET request to an API and expecting the result as a string that can be split. GetServiceProviderId() { this.http.get(this.rooturl + 'info', { headers: this.reqHeader ...

Tips for creating a VueJS method using JavaScript code?

Check out my codepen link here export default { data() { return { expanded: false, }; }, methods: { var checkList = document.getElementById('list1'); checkList.getElements ...

While the Angular application in VS Code may be successfully compiled, the most recent changes may not appear in the browser

Lately, while working on my angular application using Visual Studio Code as my code editor, I encountered two unexpected issues that have been causing me trouble. After running the command ng serve in the terminal, I receive a √ Compiled successfully. ...

Angular6 HttpClient: Unable to Inject Headers in Get Request for Chrome and IE11

Under my Angular 6 application, I am attempting to make a GET request while injecting some custom Headers: Here is how my service is structured: @Injectable() export class MyService { constructor(public httpClient: HttpClient) { } getUserInfos(login): Ob ...

I prefer to conceal the permission-wrapper component tag in the DOM when using Angular

Looking to hide the permission-wrapper component tag from appearing in the DOM. CRUCIAL: The component itself should conceal the component's tag (such as ), and instead display the template's content when necessary. For example, let's crea ...

Convert a fresh Date() to the format: E MMM dd yyyy HH:mm:ss 'GMT'z

The date and time on my website is currently being shown using "new date()". Currently, it appears as: Thu May 17 2018 18:52:26 GMT+0530 (India Standard Time) I would like it to be displayed as: Thu May 17 2018 18:43:42 GMTIST ...

Discover the method for extracting a URL from a string using jQuery or JavaScript

Here are some example URLs: http://192.168.6.1/Images/Work3ererg.png http://192.168.6.1/Images/WorwefewfewfefewfwekThumb.png http://192.168.6.1/Images/ewfefewfewfewf23243.png http://192.168.6.1/Images/freferfer455ggg.png http://192.168.6.1/Images/regrgrge ...

Error encountered in Angular10: XHR request for POST failed due to browser blocking HTTP Request to a domain with a similar name

I am encountering an issue with my webpage that consists of a Django REST API and an Angular 10 Frontend SPA. Normally, I can successfully send GET, POST, PUT, and DELETE XHR Requests to my backend without any problems. However, there is a specific API End ...

Preview your uploaded image before finalizing

I am currently working on implementing a new upload feature for users of our forum. This feature will allow them to upload a personal picture. Here is what I have developed so far: HTML <label>Profile image</label> <div class="phot ...

What causes the discrepancy between the response.headers in Angular and the response headers shown in the browser's developer

this.http.post(this.url+"/login",formData).subscribe( (response: any)=>{ console.log(response.headers); const cookies = response.headers.get('Set-Cookie'); // console.log(response.headers); console.log(c ...

Place a list with scrolling and overflow features side by side

Having trouble getting my headers to scroll with overflow auto and white-space nowrap. Can't figure out why it's not working. I want to create hyperlinks within headers to link to specific parts of the website. I have the code for hyperlinking s ...

Ways to display an HTML code by utilizing the onclick() function through PHP?

I have a button that looks like this: <input type="submit" name="submit5" class="btn" value="Add Date" onclick="create_date_field()" /> Every time the button is clicked, I want to append the following code inside the <tr> tags. It should be po ...

I encountered an issue when trying to import a React.js component in TypeScript. The .d.ts file was created by myself, but I received the error message "Module not found: Can't resolve 'xxx' in 'xxx'"

I included the TypeScript definition file for a component in my project: /// <reference types="react" /> declare namespace __ReactAvatarEditor { interface croppingRect { x: number, y: number, width: number, height: number } interf ...

ng-display does not display content when the condition switches to true

I am facing an issue with displaying an image and a YouTube video in my HTML. My goal is to show the image when the video is not playing, and switch to displaying the video when it starts playing. Upon loading the page, only the image is shown, which is ...

Implementing security measures for my RESTful API using API Key and Secret on Express

After successfully creating a REStful API using Express, my next goal is to enhance its security by implementing authentication that involves utilizing a Public key, Hashed Private Key, and a Nonce as Headers, similar to the practices followed by platfor ...

Using Jquery to duplicate an element without assigning a different name

Currently, I am working on a project using CakePHP. While I don't have much experience with jQuery, I need to clone an input/select field for a form using the jQuery .clone() function. Despite my efforts, the script I wrote isn't working as expec ...