[英]How to merge or append the array of objects to another array of object in JavaScript
How to merge the array of objects to another array of objects in JavaScript
如何将对象数组合并到 JavaScript 中的另一个对象数组
Hi everyone, below I added my code.大家好,下面我添加了我的代码。
const options = ["Fruit", "Vegitables", "Drinks"];
const mainArray=[{
Type:'Fruit',
Name:'apple',
Amount:'20'
},
{
Type:'Fruit',
Name:'apple',
Amount:'20'
},
{
Type:'Vegitables',
Name:'tomoto',
Amount:'50'
},
{
Type:'Vegitables',
Name:'onion',
Amount:'20'
},
{
Type:'Drinks',
Name:'Milk',
Amount:'30'
},
{
Type:'Drinks',
Name:'Juice',
Amount:'20'
}
]
///Filtering By Type
const filterByType=()=>{
let allMergedData=[];
selectedtypes?.map((type)=>{
let mergedData=[];
let filteredData= mainArray?.filter(x=>x.Type===type.toLowerCase());
mergedData=[...filteredData];
allMergedData=[...mergedData, ...filteredData];
})
return allMergedData;
};
return(
<div>
{options.map((option) => (
<MenuItem key={option} value={name}>
<Checkbox value={option}
onChange={handleChange}
checked={selected.includes(option)} />
<ListItemText primary={option} />
</MenuItem>
))}
</div>
)
Expected Output is: While I select the checkbox fruit and vegetable, that time I pass the fruit and vegetable values in the filterByType method.
预期的 Output 是: 而我 select 复选框水果和蔬菜,那个时候我通过 filterByType 方法中的水果和蔬菜值。 After filtering the data I need the output like a single array of objects.
过滤数据后,我需要 output 就像单个对象数组一样。
[{
Type:'Fruit',
Name:'apple',
Amount:'20'
},
{
Type:'Fruit',
Name:'apple',
Amount:'20'
},
{
Type:'Vegitables',
Name:'tomoto',
Amount:'50'
},
{
Type:'Vegitables',
Name:'onion',
Amount:'20'
},]
you can use spread operator for this您可以为此使用扩展运算符
const merged = [...person,...clothing]
var person=[{"name":"Billy","age":34},{"name":"Billy","age":34}];
var clothing=[{"shoes":"nike","shirt":"long sleeve"},{"shoes":"nike","shirt":"long sleeve"}];
var mergedV1 = [...person, ...clothing]
var mergedV2 = person.concat(clothing)
Use spread ES6 syntax https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Spread_syntax使用传播 ES6 语法https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Spread_syntax
var person=[{"name":"Billy","age":34},{"name":"Billy","age":34}]; var clothing=[{"shoes":"nike","shirt":"long sleeve"},{"shoes":"nike","shirt":"long sleeve"}]; var merge = [...person, ...clothing] console.log(merge)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.