gpt4 book ai didi

JavaScript:有条件地将 JSON 对象从一个数组添加到另一个数组

转载 作者:行者123 更新时间:2023-11-30 07:23:04 27 4
gpt4 key购买 nike

我想合并 JSON。我有两个 JSON 数组,想将对象从一个数组添加到另一个具有相同值的数组

产品

"Products": [
{
"Date": "2015-04-28T12:30:19.107",
"Code": "003UYTX1A",
"Title": "Divatex Dots Microfiber Queen Bed In the Bag",
"Description": "Go crazy with lots of dots with Divatex,
"Weight": 7.60,
"WeightUnit": "pounds",
"AverageRating": 4.1,
"EstimatedSalesPerDay": 761,
"ProfitScore": 50,
"UpdateStatus": 0,
"VersionCode": 23
},
{
"Date": "2015-04-28T12:29:46.66",
"Code": "05461AQDV",
"Title": "Wilton 1912-1294 100 Count Party Bags",
"Description": "Some Description,
"Weight": 8.10,
"WeightUnit": "pounds",
"AverageRating": 4.0,
"EstimatedSalesPerDay": 711,
"ProfitScore": 45,
"UpdateStatus": 0,
"VersionCode": 23
}]

细节

"Detail": [
{
"Date": "2015-04-28T12:29:45.95",
"Code": "003UYTX1A",
"CategoryId": "1055398",
"CategoryTitle": "Some Title",
"TotalReviews": 31
},
{
"Date": "2015-04-28T12:29:45.95",
"Code": "05461AQDV",
"CategoryId": "1055398",
"CategoryTitle": "Title",
"TotalReviews": 211
},
{
"Date": "2015-04-28T12:29:45.95",
"Code": "003UYTX1A",
"CategoryId": "1055398",
"CategoryTitle": "Category Title",
"TotalReviews": 101
}]

我需要根据相同的 Code 值组合这些数组对象,如下所示

      "Combined": [
{
"Date": "2015-04-28T12:30:19.107",
"Code": "003UYTX1A",
"Title": "Divatex Dots Microfiber Queen Bed In the Bag",
"Description": "Go crazy with lots of dots with Divatex,
"Weight": 7.60,
"WeightUnit": "pounds",
"AverageRating": 4.1,
"EstimatedSalesPerDay": 761,
"ProfitScore": 50,
"UpdateStatus": 0,
"VersionCode": 23,
"Detail":[
{
"Date": "2015-04-28T12:29:45.95",
"Code": "003UYTX1A",
"CategoryId": "1055398",
"CategoryTitle": "Some Title",
"TotalReviews": 31
},
{
"Date": "2015-04-28T12:29:45.95",
"Code": "003UYTX1A",
"CategoryId": "1055398",
"CategoryTitle": "Category Title",
"TotalReviews": 101
}]
},
{
"Date": "2015-04-28T12:29:46.66",
"Code": "05461AQDV",
"Title": "Wilton 1912-1294 100 Count Party Bags",
"Description": "Some Description,
"Weight": 8.10,
"WeightUnit": "pounds",
"AverageRating": 4.0,
"EstimatedSalesPerDay": 711,
"ProfitScore": 45,
"UpdateStatus": 0,
"VersionCode": 23,
"Detail":[
{
"Date": "2015-04-28T12:29:45.95",
"Code": "05461AQDV",
"CategoryId": "1055398",
"CategoryTitle": "Title",
"TotalReviews": 211
}]
}]

获得所需结果的任何最佳想法?我必须用 javascript 编写代码。

最佳答案

如果你使用下划线,你可以很容易地做到这一点, http://underscorejs.org/

 _.each(products,function(product,index){

var detail = _.where(details,{'Code' : product.Code})
if(detail){
product.details=detail;
}
products[index] = product
})

关于JavaScript:有条件地将 JSON 对象从一个数组添加到另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30663005/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com