Javascript,返回匹配的第一个(子)对象

时间:2017-01-24 16:42:47

标签: javascript lodash

我有一个对象数组,我试图通过它来获取与我给它的某个对象相匹配的第一个子对象。所以我的对象看起来像这样:

const filteredVariants = [
{
   name: "Test0",
   images: [
   {
    name: "test0img1",
    shot_type: "swatch"
   }]
   }, {
   name: "Test1",
   images: [
   {
    name: "test1img1",
    shot_type: "product"
   },
   {
    name: "test1img2",
    shot_type: "product"
   }]
}]

所以我要做的是查看这个对象,特别是在images内部,找到第一个有shot_type: "product"的对象并返回该对象。所以,在这种情况下,我试图让它回到我身边:

{
name: "test1img1",
shot_type: "product"
}

这是我到目前为止所做的:

 const firstProductImage = _.find(filteredVariants, _.flow(
    _.property('images'),
    _.partialRight(_.some, { shot_type: 'product' })
 ));

当我只需要子图像对象时,除了它返回整个父对象之外,这是部分方式。我试过跑过地图和过滤器,但这些方法并不像这个那么干净。我想知道在这种情况下是否有办法告诉lodash只返回匹配{ shot_type: 'product' }的第一个子节点。

我正在使用lodash,但如果在普通的javascript中这是可能的,那也会很棒。谢谢!

4 个答案:

答案 0 :(得分:1)

您可以迭代filteredVariantsimages,如果找到,则将对象分配给result。返回的truthy值结束两个循环。

Array#some的版本:

var filteredVariants = [{ name: "Test0", images: [{ name: "test0img1",  shot_type: "swatch" }]}, { name: "Test1", images: [{ name: "test1img1",  shot_type: "product" }, { name: "test1img2", shot_type: "product" }] }],
    result;

filteredVariants.some(variant =>
    variant.images.some(image => image.shot_type === "product" && (result = image))
);

console.log(result);

包含Array#reduceArray#find的版本:

var variants = [{ name: "Test0", images: [{ name: "test0img1",  shot_type: "swatch" }]}, { name: "Test1", images: [{ name: "test1img1",  shot_type: "product" }, { name: "test1img2", shot_type: "product" }] }],
    result = variants.reduce((r, variant) =>
        r || variant.images.find(image => image.shot_type === "product"),
        undefined
    );

console.log(result);

答案 1 :(得分:1)

const productImage = _.reduce(filteredVariants, (acc, item) => {
  return acc || _.find(item.images, image => image['shot_type'] === 'product')
}, undefined);

工作小提琴:https://jsfiddle.net/adrice727/dua6kryd/1/

答案 2 :(得分:1)

以下内容如何:

const filteredVariants = [
{
   name: "Test0",
   images: [
   {
    name: "test0img1",
    shot_type: "swatch"
   }]
   }, {
   name: "Test1",
   images: [
   {
    name: "test1img1",
    shot_type: "product"
   },
   {
    name: "test1img2",
    shot_type: "product"
   }]
}]

var searchObject = { shot_type: 'product' };


//   V------------ implementation here
var foundObject = _.reduce(
    filteredVariants, 
    (last, next) => last || _.find(next.images, searchObject), 
    null
);


console.log(foundObject);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

答案 3 :(得分:1)

这绝对是可能的,而且在普通的js中可能不那么令人困惑:

short int v = -12345;
unsigned short uv = (unsigned short) v;
printf("%u\n", v); // output "53191\n"