【问题标题】:Lodash append object from another object without replacementLodash 从另一个对象追加对象而不替换
【发布时间】:2016-12-06 10:53:18
【问题描述】:

如何在不替换的情况下将值从另一个对象附加到一个对象?

我正在尝试将 ObjectA 中的值附加到 ObjectB 作为子对象的名称。

这是 ObjectA。

如您所知,ObjectA 有 4 个子对象,每个子对象都关联一个 uid。

这是对象B

所以我试图将每个孩子的 uid 从 ObjectA 映射到 ObjectB

这就是理想代码的样子

Object.keys(ObjectA).forEach(
    (key) => _.assign(ObjectB, {'Product 07': true})
)

我尝试将每个 ObjectB 迭代注入源占位符 ES6 字符串插值,但它会失败,就像这样。

Object.keys(ObjectA).forEach(
    (key) => _.assign(ObjectB, {`${basketObject[key].uid}`: true})
)

来源(JSON)

请使用此代码将对象的 Object 转换为具有 _.mapValues 的数组的 Object 以从对象名称生成 uid

var ObjectA = _.mapValues(data, (val, index) => {
    return { ...val, index }
})


{
"Product": {
    "Product 01": {
        "approved": true,
        "brand": "MANGO",
        "category": "Woman",
        "color": "Black,Bright Pink",
        "description": "Rounded neck Chain detail Slit detail Zip fastening on the back section Inner lining · Side length 117.0 cm · Back length 135.5 cm These measures have been calculated for a S size.",
        "imageURL": "https://s11.postimg.org/612lpusf7/73025590_80.jpg",
        "name": "Chain Collar Dress",
        "price": 499,
        "purchasedUser": {
            "mgzQBxjF9NNVACh18ID1xDPtrwH2": true
        },
        "size": "S,M,L,XL"
    },
    "Product 02": {
        "approved": true,
        "brand": "MANGO",
        "category": "Man",
        "color": "Grey",
        "description": "Modern coat that suits every man",
        "imageURL": "https://s4.postimg.org/vub6umtlp/73079700_99.jpg",
        "name": "Tailored wool-blend overcoat",
        "price": 899,
        "purchasedUser": {
            "mgzQBxjF9NNVACh18ID1xDPtrwH2": true
        },
        "size": "S,M,L,XL"
    },
    "Product 03": {
        "approved": true,
        "brand": "MANGO",
        "category": "Kid",
        "color": "Dark Navy, Offwhite, Light Pink,Medium Heather Grey",
        "description": "Cotton fabric Spots print Rounded neck Short sleeve Embroidered Mango logo Decorated with sequins",
        "imageURL": "https://s16.postimg.org/xkpg8qypx/73003605_56.jpg",
        "name": "Logo cotton t-shirt",
        "price": 29.9,
        "purchasedUser": {
            "mgzQBxjF9NNVACh18ID1xDPtrwH2": true
        },
        "size": "3-4 years,5-6 years, 7-8 years, 9-10 years, 11-12 years, 13-14 years"
    },
    "Product 04": {
        "approved": true,
        "brand": "UNIQLO",
        "category": "Woman",
        "color": "Red, Natural, Navy",
        "description": "This comfortable women's shirt features the distinctive soft, warm, fuzzy feel of brushed 100% cotton flannel material. It looks great as a shirt or light outer layer, and the slightly loose cut gives it a relaxed style. The classic casual plaid design is available in a variety of colors.",
        "imageURL": "https://s11.postimg.org/48sak0lmr/69_180861.jpg",
        "name": "Flannel Check Long Sleeve Shirt",
        "price": 79.9,
        "size": "S,M,L,XL"
    },
    "Product 05": {
        "approved": true,
        "brand": "UNIQLO",
        "category": "Kid",
        "color": "Offwhite",
        "description": "Star Wars™  A long time ago in a galaxy far, far awayLong after the Jedi Knights have perished, young Luke Skywalker has a fateful encounter with Princess Leia, a leader of the Rebel forces. Luke and Leia fight alongside Han Solo, Chewbacca, R2-D2 and C-3PO against the evil forces of Darth Vader to help restore peace in the galaxy.  starwars.com  © & ™ Lucasfilm Ltd.  MATERIAL100% Cotton  CAREMachine wash cold",
        "imageURL": "https://s21.postimg.org/xdojmkx1z/01_185878.jpg",
        "name": "BOYS STAR WARS Short Sleeve Graphic T-Shirt",
        "price": 39.9,
        "size": "110cm,120cm,130cm,140cm,150cm"
    },
    "Product 06": {
        "approved": true,
        "brand": "UNIQLO",
        "category": "Man",
        "color": "White,Dark Grey, Navy",
        "description": "This amazing men's polo is made from next-generation, high-tech DRY-EX material. It dries sweat incredibly quickly to keep you feeling smooth, dry, and comfortable. The soft, cotton-like texture and cut allow for easy movement and combined, offer for superb comfort. In a fashionable striped pattern, perfect for warm-weather casual looks.  MATERIAL[08Dark Gray] Body: 96% Polyester, 4% Nylon/ Rib: 100% Polyester [Other Colors] 100% Polyester  CARE[08Dark Gray] Machine wash cold, gentle cycle [Other Colors] Machine wash cold",
        "imageURL": "https://s11.postimg.org/bvm6i0ujn/00_169374.jpg",
        "name": "MEN Dry EX Short Sleeve Polo Shirt",
        "price": 99.9,
        "size": "S,M,L,XL"
    },
    "Product 07": {
        "brand": "FILANTO",
        "category": "Woman",
        "color": "Black",
        "description": "Dress to impress this festive season with our must-have dresses. Our favourite piece for for creating effortlessly chic and glamorous look comes in the form of this delicate lace number. A form-fitting silhouette hugs and flatter your curves beautifully while its minimalist design makes it easy to dress it up or down.",
        "imageURL": "https://s15.postimg.org/5qqq9496j/r1_top_fl20131894_002_a_btm_a_fl20131894.jpg",
        "name": "Casual Long Dress",
        "price": 59.9,
        "size": "S,M,L,XL"
    },
    "Product 08": {
        "brand": "HOTSHOTS",
        "category": "Kid",
        "color": "Off White",
        "description": "Update her dress collection with this beautiful printed piece. Offering a short-sleeve design, round neckline and keyhole back button fastening. This dress also showcases a vibrant butterfly print motif. Sweet and demure, all this piece needs is a pair of flats to complete the look.",
        "imageURL": "https://s16.postimg.org/ocebpd3h1/ho20129717_002_e_ho20129717.jpg",
        "name": "Casual Short Dress Knit",
        "price": 29.9,
        "size": "4-5,6-7,8-9,10-11"
    },
    "Product 09": {
        "approved": true,
        "brand": "PADINI",
        "category": "Man",
        "color": "White",
        "description": "Steeped in a solid white wash, this classic Oxford shirt gets a modern tweak with the addition of stripes across the body. It also features the iconic shirt collar, along with a chest pocket, buttoned cuffs and raised placket. This is the ultimate piece for curating both casual and formal looks.",
        "imageURL": "https://s11.postimg.org/cvmbgxg2r/r1_top_pd20131998_003_b_btm_pd20131965_002_b_pd2.jpg",
        "name": " Casual Long Sleeve Shirt",
        "price": 89,
        "size": "XS,S,M,L"
    },
    "Product 10": {
        "brand": "PONEY",
        "category": "Kid",
        "color": "Navy",
        "description": "This navy polo shirt designed with knight prints is Poney's new wardrobe classic. Made from 100% Cotton Fully Comb and Single Jersey. Features a neat polo collar, brown buttons, neckline lining in contrast fabric and leather patches.",
        "imageURL": "https://s17.postimg.org/bcpbfwrcf/6j6a5351_2_1_1.jpg",
        "name": "KNIGHT POLO SHIRT",
        "price": 119,
        "size": "7-8,9-10,11-12"
    },
    "Product 11": {
        "brand": "PONEY",
        "category": "Kid",
        "color": "Navy",
        "description": "This beautiful daisy print blouse with contrast sleeves is perfect for your best friend's birthday party. Pair with our \"Poney Daisy Print Jeans\" for a chic contemporary look or our \"Poney Tutu Skirt\" for a classic party look.",
        "imageURL": "https://s12.postimg.org/la1o7vtm5/6j6a5327_1.jpg",
        "name": "DAISY PRINT BLOUSE",
        "price": 76,
        "size": "1-2,2-3,3-4,4-5,5-6"
    },
    "Product 12": {
        "brand": "GAMESTERS",
        "category": "Kid",
        "color": "Grey",
        "description": "Ensure your little one is clothed in comfort and style with this super-cool and adorable jogger shorts from Gamester. Complete with an allover repetitive print, elasticated-drawstring waist, two front side pockets and one back pocket. Complement this shorts with any printed tee to complete his look.",
        "imageURL": "https://s14.postimg.org/tz3xvg3z5/gm20130687_002_e_gm20130687.jpg",
        "name": "Casual Knit Shorts",
        "price": 29.9,
        "size": "6-7"
    }
}
}

【问题讨论】:

标签: javascript arrays object lodash


【解决方案1】:

它应该可以工作

_.mapValues(ObjectA, (val) => {
    ObjectB[val.uid] = true;
})

【讨论】:

  • 感谢您的输入,但它不会追加而是替换现有对象...
  • @J.Doe 什么?!逆天!发布您的输入数据
  • 我已经在我的帖子中更新了我的来源,请看一下
  • @J.Doe 哎呀,检查这个 jsfiddle.net/stasovlas/btqgm66p 源 - objectA 还是 objectB ?
  • 我尝试了你最新的代码,它确实不会追加......它只会替换...... source-ObjectA,我已经更新了我的代码,请将源映射到对象的对象到在继续之前先处理数组对象
【解决方案2】:

您可以使用reduce 将您的对象映射到另一个对象;

var objects = [ // Your objects, this is just dummy data
    { uuid: 'Product 01', approved: true },
    { uuid: 'Product 02', approved: true },
    { uuid: 'Product 03', approved: true }
]

var items = objects.reduce(function (prev, current) {
    prev[current.uuid] = current.approved;
    return prev;
}, {});

【讨论】:

  • 第一行,将map改为reduce
猜你喜欢
  • 2019-01-04
  • 1970-01-01
  • 2016-10-20
  • 2012-12-05
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
相关资源
最近更新 更多