简体   繁体   English

将数组对象推送到新对象

[英]push array object to new object

I have the following data: 我有以下数据:

var data = [{
    County: "Cork",
    date: '1/1/2018',
    num: 100
}, {
    County: "Roscommon",
    date: '07/10/2017',
    num: 27
}];
var Counties = {};
for (County in data) {
    for (var i = 0; i <= 1; i++) {
        Counties[data[i].County] = data[i].County;
    }
}

This returns {County: "Roscommon"} 返回{County: "Roscommon"}

How can I get my code to return every County in the array object so that I end up with: 我如何获取代码以返回数组对象中的每个县,以便最终得到:

{County: "Cork"}
{County: "Roscommon"}

You can use array#map . 您可以使用array#map You can iterate on your array using the array#map and in its callback function, you can use object destructuring syntax to get the County value and using the object short-hand notation create the object with County value. 您可以使用array#map对其数组进行迭代,并在其回调函数中使用对象分解语法来获取County值,并使用对象简写表示法使用County值创建对象。

 var data = [{ County: "Cork", date:'1/1/2018', num:100 },{ County: "Roscommon", date: '07/10/2017', num:27 }], counties = data.map(({County}) => ({County})); console.log(counties); 

You can use the array#map function. 您可以使用array#map函数。

const countyArray = data.map(el => {el.County})

or 要么

const counties = [];
for (let county of data) {
   counties.push({ County })
}

As an object: 作为对象:

const counties = {}; 

for (let element of data) { 
counties[element.County] = {County: element.County};
}

Do you mean this? 你是这个意思吗 an array with objects with only the county values? 只包含县值的对象组成的数组?

 var data = [{ County: "Cork", date:'1/1/2018', num:100 },{ County: "Roscommon", date: '07/10/2017', num:27 }]; var Counties=data.map(function(a){return {County:a.County}}); console.log(Counties); 

Or this, an array with just the county names? 还是这个,只有县名的数组?

 var data = [{ County: "Cork", date:'1/1/2018', num:100 },{ County: "Roscommon", date: '07/10/2017', num:27 }]; var Counties=data.map(function(a){return a.County}); console.log(Counties); 

For simple data mapping in an array I suggest you delve deeper in the functionality of map, which makes it pretty easy to "clean up" data in arrays to pick and choose the tidbits you want in the format you want it. 对于数组中的简单数据映射,建议您深入了解map的功能,这很容易“清理”数组中的数据以选择所需格式的花絮。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map

If you need unique values you need a couple of extra steps 如果您需要唯一的值,则需要几个额外的步骤

 var data = [{ County: "Cork", date:'1/1/2018', num:100 },{ County: "Roscommon", date: '07/10/2017', num:27 }, { County: "Roscommon", date: '17/10/2017', num:34 } ]; console.log("#nofilter"); var counties=data.map(function(a){ return a.County }); console.log(counties); console.log("as filtered array"); var counties=data.map(function(a){ return a.County; }) .filter(function(value, index, self) { return self.indexOf(value) === index; }); console.log(counties); console.log("as filtered objects"); var counties=data.map(function(a){return a.County}) .filter(function(value, index, self) { return self.indexOf(value) === index; }) .map(function(a) { return {County: a} }); console.log(counties); 

Your code has some issues, let's annalye them: 您的代码有一些问题,让我们来解决一下:

Your approach: 您的方法:

var Counties={};
for (County in data){
  for (var i=0;i<=1;i++){
     Counties["County"]=data[i].County;
  }
}

The keyword in isn't well used here, because that operator returns the index for every item in your Array data 此处没有很好地使用关键字in ,因为该运算符返回Array data每个项目的索引

for (County in data)
            ^

You don't need that inner for-loop because you can iterate over data array directly :-) 您不需要该内部for-loop因为您可以直接遍历data数组:-)

for (County in data){
   for (var i=0;i<=1;i++){ // Remove that line
   ^

As you state in your question, your desired output is an array of objects. 当您在问题中陈述时,所需的输出是对象数组。 So you need to declare an Array. 因此,您需要声明一个数组。

var Counties={};
^

Look this code snippet, it's cleaner and follow your logic: 看下面的代码片段,它更干净并遵循您的逻辑:

 var data = [{ County: "Cork", date: '1/1/2018', num: 100 }, { County: "Roscommon", date: '07/10/2017', num: 27 }]; var array = []; for (c in data) { array.push({"County": data[c].County}); } console.log(array); 

See?, your logic is working now! 看到吗?,您的逻辑正在起作用!

A short approach using reduce function will be: 使用reduce函数的一种简短方法是:

The reduce won't modify your original Object. reduce将不会修改您的原始对象。

 var data = [{ County: "Cork", date: '1/1/2018', num: 100 }, { County: "Roscommon", date: '07/10/2017', num: 27 }]; var counties = data.reduce((a, c) => { return [...a, ...[{"county": c.County}]] }, []); console.log(JSON.stringify(data)); console.log(JSON.stringify(counties)); 

See?, your original Obj wasn't modified and a new Array with the counties was created. 看到吗?您的原始Obj未被修改,并且创建了带有县的新Array。

Another short approach using map function will be: 使用map功能的另一种简短方法是:

The map won't modify your original Object. map不会修改您的原始对象。

 var data = [{ County: "Cork", date: '1/1/2018', num: 100 }, { County: "Roscommon", date: '07/10/2017', num: 27 }]; var counties = data.map((c) => ({"county": c.County})); console.log(JSON.stringify(data)); console.log(JSON.stringify(counties)); 

See?, your original Obj wasn't modified and a new Array with the counties was created. 看到吗?您的原始Obj未被修改,并且创建了带有县的新Array。

Resources 资源资源

Probably the best option is to map over the data array like so. 最好的选择可能是像这样在数据数组上进行映射。 ` `

var data = [{
    county: "Cork",
    date:'1/1/2018',
    num:100
  },{
    county: "Roscommon",
    date: '07/10/2017',
    num:27
  }];
var counties=[];
data.map(item => {
var county = {county: item.county};
counties.push(county);
});

` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM