Home > Blockchain >  make new array combination of others
make new array combination of others

Time:06-02

First array -

var a = [
"2022-01",
"2022-02",
"2022-03",
"2022-04",
"2022-05",
"2022-06",
"2022-07",
"2022-08",
"2022-09",
"2022-10",
"2022-11",
"2022-12"

]

Second Object: { "2022-05": 44922, "2022-06": 25 }

The Output that I want should be like this: -

var c = [{date: 2022-01, value:'' },{date: 2022-02, value:'' },{date: 2022-03, value:'' },{date: 2022-04, value:'' },{date: 2022-05, value:44922 },{date: 2022-06, value:25 },{date: 2022-07, value:'' },{date: 2022-08, value:'' },{date: 2022-09, value:'' },{date: 2022-10, value:'' },{date: 2022-11, value:'' },{date: 2022-12, value:'' }]

If Corresponding dates value is present in object, then on new array value should be that value otherwise it should be blank.

I tried it with many ways, but couldn't find any solution as I am very new to Javascript.

Anyone can help me on that , Please !

CodePudding user response:

var a = [
"2022-01",
"2022-02",
"2022-03",
"2022-04",
"2022-05",
"2022-06",
"2022-07",
"2022-08",
"2022-09",
"2022-10",
"2022-11",
"2022-12"
];
var b =  { "2022-05": 44922, "2022-06": 25 };

var c = a.map(date => ({date, value: b[date] || ''}));

console.log(c);

I'm using .map() to loop through array a, returning a new object for each iteration. More info: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/map

This object's value is trying to find the corresponding value in b ( b[date] ), in case it doesn't find anything ( b[date] === undefined ), then its setting an empty string.

CodePudding user response:

It is very simple, just create a transform function and check if the value exists in the json from array, this will run in any version of javascript and it also doesn't use any in-built js array function. Easy to understand

var a = [
"2022-01",
"2022-02",
"2022-03",
"2022-04",
"2022-05",
"2022-06",
"2022-07",
"2022-08",
"2022-09",
"2022-10",
"2022-11",
"2022-12"
]

var b = { "2022-05": 44922, "2022-06": 25 };

function transformObject(a, b) {
    var res = [];
    for (i in a) {
        res.push({
            date : a[i],
            value : b[a[i]] || ''
        })
    }
    return res;
}

var result = transformObject(a, b)

  • Related