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

Using jQuery to handle nested div elements and triggering a click event only once when the inner div is clicked

I have a situation where I have nested divs. When the inner div (closeme) is clicked, I do not want the click event of the outer div (container) to be triggered. How can I achieve this? html <div id="container"> content <div id="closeme">< ...

Issue with AngularJS: Unable to receive response from REST API call

I'm currently working on developing a basic login form using AngularJS and a RESTful web service. While I've been able to successfully call the RESTful web service, I am struggling to retrieve the response. 1) Login Form: <div class="col-md- ...

Exploring the power of Vue element manipulation

I'm diving into the world of web development and starting my journey with Vue on an online learning platform. Check out the code snippet below: <div id="app"> <form @submit.prevent="onSubmit"> <input v-model="userName"&g ...

Exploring the functionality of Angular.js through QUnit testing

Is it possible to integrate angular.mock.inject() with QUnit instead of Jasmine? In the provided code snippet, angular.mock.dump is defined, but unfortunately angular.mock.inject remains undefined. <!DOCTYPE html> <html ng-app="mymodule"> & ...

Receiving the error message "SyntaxError: Unexpected token {" while attempting to send JSON with an AngularJS HTTP POST request

RESOLVED: After troubleshooting, I discovered that the issue was caused by the second echo statement in my PHP script. Once I removed it and only kept the first one, everything worked smoothly. I'm facing a problem while trying to make a simple post ...

Traversing an array and connecting each element to a separate array in AngularJS

In my programming task, I am working with an object and an array that are defined as follows: $scope.multipleTransferGotten = []; $scope.newParameters = { UserId: "", Udid:"", TransType: "", SourceAccNumber: "" ...

What is the best approach to deserialize JSON that may contain either an object or an empty array, and if it is an object, it is in a "Dictionary" format?

I have encountered JSON data in a specific format that I cannot control. The data includes information about different countries, their codes, and names. { "response": { "status": 1, "httpStatus": 200, ...

Customize and Enhance Code for Website Integration

My code is fetching a script from an external website. var url = "//example.com/script-url.js"; $.ajax({ url: url, dataType: 'jsonp' }); Although it functions properly, the script retrieved is created by a different website. I need to make ...

Rails is unable to store the JSON request as a parameter

I am attempting to save the token parameter that is received from a JSON request, but for some reason, I cannot confirm if it is actually being saved. My observation is that when a POST request with JSON parameters is made, Rails routes it to the create me ...

The setCountry function fails to properly change the country value

My goal is to establish a default country selection in checkbox options, I have three choices: United States, United Kingdom, and Rest of the world; Here's the constant called AVAILABLE_COUNTRIES which contains the iso codes for the mentioned countrie ...

The criteria set by jQuery are met

I have developed my own custom form validation for two inputs: one for a phone number and the other for an email address. Additionally, I have integrated two forms on a single page. Here is a snippet of my code: var email, phone; if (email address passe ...

Having trouble getting the onPress event to function properly on a custom button component in my React Native application

As a React Native beginner, I am currently working on a project where I am trying to create a custom button named "RoundedButton" using TouchableOpacity. However, when I attempt to trigger an event using onPress like , it does not seem to work for me. Here ...

Troubleshooting issues with jQuery `.live()` event not triggering as expected

In a project I am working on, I have implemented complex AJAX functionality to fetch inner page content from a WordPress blog. Due to the dynamic nature of the site, where the DOM is replaced after page load via AJAX, I have opted to use jQuery's .liv ...

Looking for Precise Matching within JSON Using JavaScript

I've been experimenting with creating a form that submits data and then checks it against a JSON array to see if there's a matching object already present. Here is a snippet of my JSON data for reference: [ { "ASIN":"B0971Y6PQ3 ...

Having trouble accessing AJAX POST data in Python?

For this jQuery request, I utilize an HTTP POST. function retrieveData() { const information = JSON.stringify({ "test_id": "1" }); jQuery.post('/retrieveData', information, function (response) { a ...

A guide on invoking a JavaScript function within a dropdown menu based on selection instead of change event

I need to automatically trigger a JavaScript function based on the value pulled from the dropdown options that are populated by a database. Currently, the JavaScript function only runs when I manually select an option on the front-end. Below is my code. I ...

Error message encountered while using SPARK: read.json is triggering a java.io.IOException due to an excessive number

Encountering an issue while trying to read a large 6GB single-line JSON file: Error message: Job aborted due to stage failure: Task 5 in stage 0.0 failed 1 times, most recent failure: Lost task 5.0 in stage 0.0 (TID 5, localhost): java.io.IOException: Too ...

A guide on testing mouse clientY in React using JEST for effective testing

useEffect(() => { const mouseHandler = (event: MouseEvent) => { menuData.forEach((element) => { if (element.hasActiveDropdown && event.clientY > 50) { handleCloseDropDown(); // handleDropDown('0') ...

Enabling direct access to sub-folder files within the root of npm imports

A new npm module I am creating has a specific folder structure: lib/ one-icon.jsx another-icon.jsx /* about 100 more */ package.json I would like to import these files in this manner: import OneIcon from 'icon-package/one-icon'; However ...

Restrict the option to select checkboxes

Can anyone help with limiting checkbox selection? This is the code I currently have... foreach($res as $res) echo '<div class="ediv"><input type="checkbox" class="echeck" name="pr[]" value="'.trim($res['product']).'" ...