最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript merge two arrays with forEach - Stack Overflow

matteradmin7PV0评论

I want to construct a new array based on two sets of arrays. My current attempt is:

const mylist = [
            {
                "city" : "aa", 
                "country" : "de"
            },
            {
                "city" : "bb", 
                "country" : "us"
            },
            {
                "city" : "cc", 
                "country" : "ca"
            },
            {
                "city" : "dd", 
                "country" : "za"
            },
            {
                "city" : "ee", 
                "country" : "fr"
            },            
            {
                "city" : "ff", 
                "country" : "gr"
            }                      
        ]


const stats = [{name : 'original', count: 'one'}, {name: 'copy', count: 'two'}, {name: 'redundant', count: 'three'}];

let myFinalList = [];
let str = 'hello.';


mylist.forEach(function (place, nn) {
  let suffix = place.country;
  stats.forEach(function (k) {
    let items = {};
    items[k.name] = str + k.count + '.' + suffix;
    items['city'] = place.city;
    myFinalList.push(items);
  });

}, this);

console.log('print out: ', myFinalList);

the expected result is:

[ { original: 'hello.one.de', copy: 'hello.two.de', redundant: 'hello.three.de', city: 'aa' },
  { original: 'hello.one.us', copy: 'hello.two.us', redundant: 'hello.three.us', city: 'bb' },
  ...
  { original: 'hello.one.gr', copy: 'hello.two.gr', redundant: 'hello.three.gr', city: 'ff' }]

could somebody help me achieve this goal? i am confused and can't get the right array structure.

I want to construct a new array based on two sets of arrays. My current attempt is:

const mylist = [
            {
                "city" : "aa", 
                "country" : "de"
            },
            {
                "city" : "bb", 
                "country" : "us"
            },
            {
                "city" : "cc", 
                "country" : "ca"
            },
            {
                "city" : "dd", 
                "country" : "za"
            },
            {
                "city" : "ee", 
                "country" : "fr"
            },            
            {
                "city" : "ff", 
                "country" : "gr"
            }                      
        ]


const stats = [{name : 'original', count: 'one'}, {name: 'copy', count: 'two'}, {name: 'redundant', count: 'three'}];

let myFinalList = [];
let str = 'hello.';


mylist.forEach(function (place, nn) {
  let suffix = place.country;
  stats.forEach(function (k) {
    let items = {};
    items[k.name] = str + k.count + '.' + suffix;
    items['city'] = place.city;
    myFinalList.push(items);
  });

}, this);

console.log('print out: ', myFinalList);

the expected result is:

[ { original: 'hello.one.de', copy: 'hello.two.de', redundant: 'hello.three.de', city: 'aa' },
  { original: 'hello.one.us', copy: 'hello.two.us', redundant: 'hello.three.us', city: 'bb' },
  ...
  { original: 'hello.one.gr', copy: 'hello.two.gr', redundant: 'hello.three.gr', city: 'ff' }]

could somebody help me achieve this goal? i am confused and can't get the right array structure.

Share Improve this question asked Nov 23, 2017 at 3:12 moaningalwaysmoaningalways 4611 gold badge10 silver badges21 bronze badges 1
  • 1 Looks like you're declaring items in side the foreach. Could be wrong but I think you want to do it outwith the loop itself. – CBusBus Commented Nov 23, 2017 at 3:15
Add a ment  | 

2 Answers 2

Reset to default 2

i think you are missing the right position to declare the variables:

mylist.forEach(function (place, nn) {
  let suffix = place.country;
  let items = {};
  stats.forEach(function (k) {

    items[k.name] = str + k.count + '.' + suffix;

  });
    items['city'] = place.city;
    myFinalList.push(items);
}, this);

Why not we try using .map() and .reduce() and Template literals ?

/* transform every place in mylist ...*/
var finalList = mylist.map(place => {
    /*  1. create a new ITEM object with CITY property set with PLACE.CITY.
        2. for each stat, create a new property in ITEM and set its value with string interpolation..
        3. return ITEM as the transformed object...*/
    return stats.reduce((item, stat) => {
        item[stat.name] = `${str}.${stat.count}.${place.country}`;
        return item;
    }, { city: place.city });
});

var mylist = [
	{ city: "aa", country: "de"	}, 
	{ city: "bb", country: "us"	}, 
	{ city: "cc", country: "ca"	}, 
	{ city: "dd", country: "za"	}, 
	{ city: "ee", country: "fr"	}, 
	{ city: "ff", country: "gr"	}
];

var stats = [
	{ name: 'original', count: 'one' }, 
	{ name: 'copy', count: 'two' }, 
	{ name: 'redundant', count: 'three' }
];

var str = 'hello';
/* transform every place in mylist ...*/
var finalList = mylist.map(place => {
		/* 	1. create a new ITEM object with CITY property set with PLACE.CITY.
			2. for each stat, create a new property in ITEM and set its value with string interpolation..
			3. return ITEM as the transformed object...*/
		return stats.reduce((item, stat) => {
			item[stat.name] = `${str}.${stat.count}.${place.country}`;
			return item;
		}, { city: place.city });
	});

console.log('print out: ', finalList);

Post a comment

comment list (0)

  1. No comments so far