What is the method for assigning a value to a JSON object using data from another JSON object?

I am faced with the task of setting the seqNo property in one JSON object, b, based on the id from another JSON object, a. How can I achieve this?

var a = [{id: "Make",   seqNo: 4},
            {id: "Model",  seqNo: 1},
            {id: "XModel", seqNo: 2},
            {id: "Rate",   seqNo: 3},
            {id: "Price",  seqNo: 0}];

var b = [
           {id: "Make", field: "make", seqNo: setvalue},
           {id: "Model", field: "model", seqNo: setvalue},
           {id: "XModel", field: "model", seqNo: setvalue},
           {id: "Rate", field: "price", seqNo: setvalue},
           {id: "Price", field: "price", seqNo: setvalue}
        ];

output:-

var c = [
            {headerName: "Make", field: "make", seqNo: 4},
            {headerName: "Model", field: "model", seqNo: 1},
            {headerName: "XModel", field: "model", seqNo: 2},
            {headerName: "Rate", field: "price", seqNo: 3},
            {headerName: "Price", field: "price", seqNo: 0}
        ];

Answer №1

Given the same sequence:

var message = "";
var x = [{id: "Type",   orderNo: 4},
         {id: "Brand",  orderNo: 1},
         {id: "ModelX", orderNo: 2},
         {id: "Cost",   orderNo: 3},
         {id: "Price",  orderNo: 0}];

var y = [{id: "Type", category: "type", orderNo: message},
         {id: "Brand", category: "brand", orderNo: message},
         {id: "ModelX", category: "model", orderNo: message},
         {id: "Cost", category: "price", orderNo: message},
         {id: "Price", category: "value", orderNo: message}
        ];

var z=[];
for (var i=0;i<x.length;i++) {
  var xItem = x[i], yItem=y[i];
  z.push({ headerName:xItem.id, field:yItem.category, orderNo: xItem.orderNo });
}
console.log(z);
document.write(JSON.stringify(z, null, 2).replace(/},/g,"},<br/>"));

Answer №2

One approach you could consider is as follows:

let convertedArray = originalArray.reduce(function(result, item) {
    result[item.key] = item.value;
    return result;
}, {});

// convertedArray => {key1: value1, key2: value2,.. }

let mappedArray = secondArray.map(function(item) {
    let newItem = {
        key: item.key,
        data: item.data,
        value: convertedArray[item.key]
    };
    return newItem;
});

This code snippet first transforms the original array into an object map and then utilizes this map to correctly match elements while mapping the second array.

Answer №3

Consider this loop-based solution for obtaining the desired outcome, assuming an equal number of objects exist in both arrays:

var array1 = [{id: "Make",   seqNo: 4},
            {id: "Model",  seqNo: 1},
            {id: "XModel", seqNo: 2},
            {id: "Rate",   seqNo: 3},
            {id: "Price",  seqNo: 0}];

var array2 = [
           {id: "Make", field: "make", seqNo: 'setvalue'},
           {id: "Model", field: "model", seqNo: 'setvalue'},
           {id: "XModel", field: "model", seqNo: 'setvalue'},
           {id: "Rate", field: "price", seqNo: 'setvalue'},
           {id: "Price", field: "price", seqNo: 'setvalue'}
        ];

array2 = array2.map(function (obj) {
    array1.forEach(function (aObj,aIndex) {
        if (obj.id == array1[aIndex].id) {
            obj["seqNo"] = array1[aIndex].seqNo;
        }
    })
    return obj;
})
console.log(array2)

// Expected result
[ { id: 'Make', field: 'make', seqNo: 4 },
  { id: 'Model', field: 'model', seqNo: 1 },
  { id: 'XModel', field: 'model', seqNo: 2 },
  { id: 'Rate', field: 'price', seqNo: 3 },
  { id: 'Price', field: 'price', seqNo: 0 } ]

Answer №4

If you're utilizing underscorejs, it is recommended to utilize the following code for merging two objects:

_.extend({id: "Make", field: "make", seqNo: setvalue}, {id: "Make", seqNo: 4})

For those using Jquery, consider using this code:

$.extend({id: "Make", field: "make", seqNo: setvalue}, {id: "Make", seqNo: 4})

If a plain javascript function is needed, it can be found at:

In situations where there are two arrays of objects, utilizing map or another method to iterate through the array and apply the extending function to each element is necessary.

Answer №5

Thank you for presenting such a thought-provoking query.

Here is my approach utilizing the underscore library:

var result = _.zipWith(values, keys, function(item1, item2) {
    var mergedObject = _.assign({}, item1, item2);
    mergedObject.title = mergedObject.key; 
    delete mergedObject.key; 
    return mergedObject;
});

console.log(result);

Answer №6

Check out this code snippet:

var colors = [{name: "Red",    id: 4},
        {name: "Green",  id: 1},
        {name: "Blue",   id: 2},
        {name: "Yellow", id: 3},
        {name: "Purple", id: 0}];

// setting null to id
var updatedColors = [
       {name: "Red", field: "redColor", id: null},
       {name: "Green", field: "greenColor", id: null},
       {name: "Blue", field: "blueColor", id: null},
       {name: "Yellow", field: "yellowColor", id: null},
       {name: "Purple", field: "purpleColor", id: null}
    ];

Assign values here:

Simply update like this:

   if(colors.length == updatedColors.length){
      for(var i=0; i<colors.length;i++){
         updatedColors[i].id = colors[i].id;
      }
    }
    else{ console.log('Error','length does not match')}

Alternatively:

You can directly assign if you have two objects:

var updatedColors = [
       {name: "Red", field: "redColor", id: colors[0].id},
       {name: "Green", field: "greenColor", id: colors[1].id},
       {name: "Blue", field: "blueColor", id: colors[2].id},
       {name: "Yellow", field: "yellowColor", id: colors[3].id},
       {name: "Purple", field: "purpleColor", id: colors[4].id}
    ]; 

Hope this explanation is clear for you...

Answer №7

If you're looking to optimize your code in JavaScript, I recommend utilizing a for loop.

var names = [{id: "Make",   seqNo: 4},
        {id: "Model",  seqNo: 1},
        {id: "XModel", seqNo: 2},
        {id: "Rate",   seqNo: 3},
        {id: "Price",  seqNo: 0}];
var fields = [
       {id: "Make", field: "make", seqNo: 0},
       {id: "Model", field: "model", seqNo: 0},
       {id: "XModel", field: "model", seqNo: 0},
       {id: "Rate", field: "price", seqNo: 0},
       {id: "Price", field: "price", seqNo: 0 }
    ];
for (var indexFields in fields) {
   for(var indexNames in names){

   var objField = fields[indexFields];
   var objName = names[indexNames];
        if(objField.id == objName.id ){
          objField.seqNo = objName.seqNo;
        }
    }
}
console.log(fields)

Check out the JSFiddle demo here

I hope this solution proves helpful and efficient for your coding needs.

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

Troubles arise when trying to load AngularJS using RequireJS within the application

I am currently developing a NodeJS application that utilizes AngularJS for its front-end. Additionally, I am integrating RequireJS to handle the loading of JavaScript dependencies and then initialize the Angular app. Here is my approach: Inside my HTML fi ...

Guide to migrating disk.db in sails.js to a MongoDB database

Currently, I have a node.js application built with the sails.js web framework. During development, I am using the sails-disk adapter and the sample data from disk.db looks like this: { "data": { "authentication": [ { ...

How about mixing up your backgrounds with an overlay effect for a unique look?

Hey there, I'm currently working on adding random backgrounds to my website through an overlay, but I've hit a roadblock when it comes to displaying them. Here is the code I'm working with: .css / .php #intro { background: ...

How to turn off automatic formatting in CKEditor

Whenever data is entered into a field using CKEditor, the Save button becomes enabled. However, if I programmatically set data into the field using Javascript, the Change event always triggers causing the Save button to remain enabled even if the field is ...

Looking to adjust the fill pattern dynamically

I previously implemented this code: Is there a way to modify the fill image on my 3 buttons to display in 3 distinct colors instead? ...

Tips for updating the content of multiple tabs in a container with just one tab in Bootstrap 4.x

I am attempting to create two tab containers, where one is used to describe the content of a set of files and the other is used as a list of download links for the described files. Initially, I tried controlling the two containers using just one tab. I ca ...

:Incorporating active hyperlinks through javascript

Hey there, I've encountered a little conundrum. I have a header.php file that contains all the header information - navigation and logo. It's super convenient because I can include this file on all my pages where needed, making editing a breeze. ...

Is PhantomJS or prerender.io still necessary for crawling websites?

I am currently updating a project where I have switched to using AngularJS on the frontend. However, I encountered an issue with serving pages to crawlers. We do not use Akamai locally, but it is implemented on staging and production (using the old stack). ...

Issues with the functionality of the shopping cart are causing a disruption

This is the coding for the online shopping cart: <!DOCTYPE html> <html lang="en-us"> <head> <meta charset="UTF-8" /> <title>Online Shopping Cart</title> <script src="jquery-3.1.1.min.js"></script> ...

How to use RegExp to locate the final return statement within a JavaScript code string

Take a look at this code snippet: cont x = 10; function foo() { return x; // ;; end of function ;; // /* here is a some text here too */ } function bar() { return 10 } return foo() + bar(); // ;;done;; // /* yolo yolo */ This string cont ...

"Implementing a sorting feature in a product filtering system with JavaScript/Vue, allowing

I have a dataset structured like this: > Price : ["800000","989000","780000","349000"] If the user selects 'sort by lowest price', I want the data to be arranged from the lowest price to the highest price as follows: > Price : ["349000" ...

Enhance user interactivity by incorporating dynamic checkboxes, radio buttons, checkbox groups, and radio button groups using Ext

Hello to all the amazing folks at Stack Overflow! I've tried searching for a solution to this issue on Stack Overflow, but I couldn't find anything helpful. Here is my model: Ext.define('soru', { extend: 'Ext.data.Model' ...

Passing parameters to a post request in Swift

I am facing an issue with passing parameters in my API as shown in the image. In my Swift code, I have attempted to pass these parameters but it doesn't seem to be working. Here is how I've tried: let header: HTTPHeaders = ["Content-Type": "appl ...

Is it possible to customize the close icons on the autocomplete feature in Material UI?

Is there a solution to change the icon while keeping its function when clicked? I am looking to replace this Icon <Autocomplete multiple id="checkboxes-tags-demo" options={top100Films} disableCloseOnSelect getOpt ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...

Encountering issues with the Sequelize Model.prototype.(customFunction) feature malfunctioning

While attempting to define a customFunction within the Sequelize model, I encountered an error: TypeError: user.getJWT is not a function at User.create.then (/projects/test/a/app/controllers/UserController.js:22:29) Below is the code snippet from ...

What are the proper methods for accurately testing vuex state and mutations?

Can someone guide me on how to properly test mutations and state? I have a modal window component that is rendered when the showModal property in the state is true. There is an event triggering a mutation that changes this property. How can I verify that a ...

Jquery fails to function properly unless the page is refreshed

On my MVC page, I have implemented a feature where certain text-boxes are shown or hidden based on the value selected in a drop-down menu using jQuery. The functionality works fine when the page is isolated, but when placed under a menu, it encounters a pr ...

Displaying Data in Table Using Ajax Request

I'm working on a project that involves creating an HTML table from an ajax request pulling SharePoint list items. The screenshot provided demonstrates how it functions and what it displays after the button is clicked. However, I am looking for a way t ...

React.js: The art of nesting components within each other

One common feature in many template languages is the use of "slots" or "yield" statements, which allow for a form of inversion of control by wrapping one template inside another. Angular offers the "transclude" option for this purpose. Ruby/Rails utilize ...