最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to add a key value pair to an array in JavascriptJquery - Stack Overflow

programmeradmin1浏览0评论

I have 2 arrays as below

var dataSource = [
{location: "France", January: 79, February: 81, March: 23},  
{location: "Germany", January: 98, February: 83},
{location: "Japan", January: 96, March: 11} ];

var Months = ["January","February","March"];

I want to loop through each object in dataSource and check if all values of Months exist in each objects of dataSource. If the value doesn't exist in dataSource then add that value to dataSource with value = 100

example : in location Germany, the month "March" does not exist so I need to push the key and value March : 100

at the end dataSource should be as below

var dataSource = [
{location: "France", January: 79, February: 81, March: 23},  
{location: "Germany", January: 98, February: 83, March: 100},
{location: "Japan", January: 96, February: 100, March: 11} ];

I tried many solutions from previous threads but I am not getting the exact result I want. Here are some of my ideas

var dataSource = [
{location: "France", January: 79, February: 81, March: 23},  
{location: "Germany", January: 98, February: 83},
{location: "Japan", January: 96, March: 11} ];

var Months = ["January","February","March"];

dataSource.forEach(function(element) {
Months.forEach(function(item) {
  if (!(item in element)) {
//Object.assign(dataSource, {item: 100}); 
//dataSource = {...dataSource, ...{item: 100}}
dataSource.push({item: 100});
  }
});
});

console.log(dataSource);

I have 2 arrays as below

var dataSource = [
{location: "France", January: 79, February: 81, March: 23},  
{location: "Germany", January: 98, February: 83},
{location: "Japan", January: 96, March: 11} ];

var Months = ["January","February","March"];

I want to loop through each object in dataSource and check if all values of Months exist in each objects of dataSource. If the value doesn't exist in dataSource then add that value to dataSource with value = 100

example : in location Germany, the month "March" does not exist so I need to push the key and value March : 100

at the end dataSource should be as below

var dataSource = [
{location: "France", January: 79, February: 81, March: 23},  
{location: "Germany", January: 98, February: 83, March: 100},
{location: "Japan", January: 96, February: 100, March: 11} ];

I tried many solutions from previous threads but I am not getting the exact result I want. Here are some of my ideas

var dataSource = [
{location: "France", January: 79, February: 81, March: 23},  
{location: "Germany", January: 98, February: 83},
{location: "Japan", January: 96, March: 11} ];

var Months = ["January","February","March"];

dataSource.forEach(function(element) {
Months.forEach(function(item) {
  if (!(item in element)) {
//Object.assign(dataSource, {item: 100}); 
//dataSource = {...dataSource, ...{item: 100}}
dataSource.push({item: 100});
  }
});
});

console.log(dataSource);

Thank you for your suggestions.

Share Improve this question asked Mar 7, 2019 at 18:37 DevTNDevTN 5932 gold badges13 silver badges37 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 6

You can use Array.map() to iterate the dataSource array. Use an internal Array.reduce() to iterate the Months, and add missing months to the current object:

const dataSource = [{"location":"France","January":79,"February":81,"March":23},{"location":"Germany","January":98,"February":83},{"location":"Japan","January":96,"March":11}];
const Months = ["January","February","March"];

const result = dataSource.map(o =>
  Months.reduce((obj, m) => m in obj ? obj : { ...obj, [m]: 100 }, o)
);

console.log(result);

You can loop through the sources and months, setting the months on the sources as the value they already have, or defaulting to 100.

var dataSource = [{
    location: "France",
    January: 79,
    February: 81,
    March: 23
  },
  {
    location: "Germany",
    January: 98,
    February: 83
  },
  {
    location: "Japan",
    January: 96,
    March: 11
  }
];

var Months = ["January", "February", "March"];

dataSource.forEach(function(element){
  Months.forEach(function(month){
    if (element[month] === undefined) element[month] = 100;
  });
});

console.log(dataSource);

Or else, you can create a hash with resultant months and their values, which you can be directly used, by assigning each object of your array on top of it. So you can process N number of inputs (arrays) with the same hash.

Example of Resultant Hash: {January: 100, February: 100, March: 100}

And then you can do this N number of time:

dataSource1.map(d => ({...hash, ...d}));
dataSource2.map(d => ({...hash, ...d}));
dataSource3.map(d => ({...hash, ...d}));

Here is the example:

let dataSource = [{"location":"France","January":79,"February":81,"March":23},{"location":"Germany","January":98,"February":83},{"location":"Japan","January":96,"March":11}],
    Months = ["January","February","March"],
    hash = Months.reduce((r, e) => ({...r, [e]: 100}), {}),
    res = dataSource.map(d => ({...hash, ...d}));
    
console.log('This is your hash: ', hash); //This is the hash generated one time
console.log('This is your result: ', res); //this is the result against that input

Maybe this can help you some. Just run test() in the developer tools or something and look at the console.log output

pay attention to the uniqueKeys object since its where the main logic is centered around and the hasOwnProperty stuff

function test() {

    var uniqueKeys = {location: ''};                        //default to have location set
    var Months = ['January', 'February', 'March'];

    for (var i = 0; i < Months.length; i++) {
        uniqueKeys[Months[i]] = '';                     //just populate the object from the array to use soon
    }


    for (var i = 0; i < dataSource.length; i++) {




        var validObject = true;
        Object.keys(uniqueKeys).forEach((e,j) => {

            if (dataSource[i].hasOwnProperty(e) === false) {
                validObject = false;
            }

        });

        if (validObject === false) {

            console.log('add to', dataSource[i], 'to balance it out');

        }
    }
}

hope it helps some ~cheers

May be this short solution that iterates over the months and checks whether that month is present in each record for datasource. If not then add default value, 100 in your case

for(i=0;i<dataSource.length;i++){
        for(j=0;j<Months.length;j++){
            if(Months[j] in dataSource[i]){
            }
            else{
                dataSource[i][Months[j]] = 100;
            }   
        }
    }
发布评论

评论列表(0)

  1. 暂无评论