如何比较对象的数组和数组,并在新数组
中插入新对象dayList
我需要将dayArray
与const result = [
{'key':'Mon','value':1},
{'key':'Tue','value':5},
{'key':'Wed','value':10},
{'key':'Thu','value':0},
{'key':'Fri','value':18},
{'key':'Sat','value':80},
{'key':'Sun','value':20},
]
进行比较,然后插入新的
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
int main()
{
//establishing constant variables;
const char Walls = '#';
const char Mazes = '-';
const int row = 10;
const int col = 11;
//defining strings to pull from text file
std::string arraysize_sx;
std::string arraysize_sy;
std::string start_sx;
std::string start_sy;
std::string finish_sx;
std::string finish_sy;
std::string walls_s;
std::ifstream openfile ("input.txt");
std::ofstream outputfile ("output.txt",std::ios::app);
//gets points from text file, using , and . as delimiters
std::getline(openfile, arraysize_sx , ',');
std::getline(openfile, arraysize_sy, '.');
std::getline(openfile, start_sx, ',');
std::getline(openfile, start_sy, '.');
std::getline(openfile, finish_sx , ',');
std::getline(openfile, finish_sy , '.');
std::getline(openfile,walls_s, '.');
int startx,starty;
int finishx,finishy;
//convert string to int
std::stringstream rowconv(arraysize_sx);
std::stringstream colconv(arraysize_sy);
std::stringstream startsx(start_sx);
std::stringstream startsy(start_sy);
std::stringstream finishsx(finish_sx);
std::stringstream finishsy(finish_sy);
// rowconv >> row;
// colconv >> col;
startsx >> startx;
startsy >> starty;
finishsx >> finishx;
finishsy >> finishy;
//defining the shape of the maze
char maze [col][row] = {
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
{'-','-','-','-','-','-','-','-','-','-'},
};
maze[startx][starty] = 's';
maze[finishx+3][finishy] = 'f';
outputfile << *maze;
openfile.close();
}
如果可以使用lodash完成吗?
答案 0 :(得分:1)
从dayList
按键创建Map天。使用Array#map迭代dayArray
,如果dayMap
中没有这一天,则返回一个空对象:
const dayList = [
{'key':'Mon','value':1},
{'key':'Tue','value':5},
{'key':'Wed','value':10},
{'key':'Fri','value':18},
{'key':'Sat','value':80},
{'key':'Sun','value':20},
]
const dayArray = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
const dayMap = new Map(dayList.map((o) => [o.key, o]))
const result = dayArray.map((key) => dayMap.has(key) ? dayMap.get(key) : { key, value: 0 })
console.log(result);
答案 1 :(得分:0)
创建JSON对象数组中所有键的数组。然后找出差异并将差异对象推送到数组。
var dayArray = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
var diff = _.difference(dayArray,_.map(dayList,'key'));
if(diff.length>0){
dayList.push({key:diff[0],value:0});
}
console.log(dayList);