【问题标题】:Nested json payload and nested array javascript interview嵌套 json 有效负载和嵌套数组 javascript 面试
【发布时间】:2021-12-10 18:36:52
【问题描述】:

将此作为 coderbyte.com 上前端位置的评估测试

我们集成了许多不同的 API 和服务。通常,在前端,我们与许多不同的产品推荐提供商集成。这通常看起来像是来自零售商的推荐产品的轮播,如果有兴趣,客户会考虑购买。产品推荐的 API 提供者具有所有不同类型的 API 响应,但我们将尝试在下面的代码中利用一种通用模式。

编写一个函数,该函数接收 JSON 有效负载和配置对象作为参数,并将 JSON 有效负载中的映射属性数组返回到可枚举值以呈现轮播。 JSON 有效负载将始终包含一个嵌套数组,该数组将包含有关要在轮播中显示的每个产品的嵌套数据。您可以定义用于读取嵌套数组和映射嵌套产品属性的配置对象。

尽量写出最高效、最简洁的代码。强烈建议使用现代函数方法,但不是必需的。

示例 1

JSON 负载输入

  "payload": [
    {
      "data": [
        [
          {
            "name": "Handbag",
            "url": "https://example.com/products/handbag",
            "images": {
              "small": "https://example.com/products/handbag/images/small.png",
              "medium": "https://example.com/products/handbag/images/medium.png",
              "large": "https://example.com/products/handbag/images/large.png"
            },
            "color": "black",
            "price": "$50.00"
          }
        ],
        [
          {
            "name": "Shoes",
            "url": "https://example.com/products/shoes",
            "images": {
              "small": "https://example.com/products/shoes/images/small.png",
              "medium": "https://example.com/products/shoes/images/medium.png",
              "large": "https://example.com/products/shoes/images/large.png"
            },
            "color": "red",
            "price": "$35.00"
          }
        ]
      ]
    }
  ]
}

预期输出

  [
    { type: 'TEXT', value: 'Handbag' },
    { type: 'URL', value: 'https://example.com/products/handbag' },
    { type: 'IMAGE', value: 'https://example.com/products/handbag/images/medium.png' },
    { type: 'TEXT', value: '$50.00' }
  ],
  [
    { type: 'TEXT', value: 'Shoes' },
    { type: 'URL', value: 'https://example.com/products/shoes' },
    { type: 'IMAGE', value: 'https://example.com/products/shoes/images/medium.png' },
    { type: 'TEXT', value: '$35.00' }
  ]
]

示例 2

JSON 负载输入

[
  [
    {
      "product_id": "000001",
      "meta": {
        "en_US": {
          "product_name": "Handbag",
          "product_urls": ["https://example.com/products/handbag"],
          "product_image_small": "https://example.com/products/handbag/images/small.png",
          "product_image_medium": "https://example.com/products/handbag/images/medium.png",
          "product_image_large": "https://example.com/products/handbag/images/large.png",
          "product_price_cents": 5000,
          "product_custom_attributes": {
            "product_price_string": "$50.00",
            "product_color": "black"
          }
        }
      }
    },
    {
      "product_id": "000002",
      "meta": {
        "en_US": {
          "product_name": "Shoes",
          "product_urls": ["https://example.com/products/shoes"],
          "product_image_small": "https://example.com/products/shoes/images/small.png",
          "product_image_medium": "https://example.com/products/shoes/images/medium.png",
          "product_image_large": "https://example.com/products/shoes/images/large.png",
          "product_price_cents": 3500,
          "product_custom_attributes": {
            "product_price_string": "$35.00",
            "product_color": "red"
          }
        }
      }
    }
  ]
]

预期输出

[
  [
    { type: 'TEXT', value: 'Handbag' },
    { type: 'URL', value: 'https://example.com/products/handbag' },
    { type: 'IMAGE', value: 'https://example.com/products/handbag/images/medium.png' },
    { type: 'TEXT', value: '$50.00' }
  ],
  [
    { type: 'TEXT', value: 'Shoes' },
    { type: 'URL', value: 'https://example.com/products/shoes' },
    { type: 'IMAGE', value: 'https://example.com/products/shoes/images/medium.png' },
    { type: 'TEXT', value: '$35.00' }
  ]
]

我的解决方案不够动态,无法解析两个输入负载。它适用于Example 1

我的解决方案

var config = {
    name: {type :"TEXT", label: "name",  key: "name"},
    url: {type :"URL", label: "url", key: "url"},
    images: {type :"IMAGE", label: "image", key: "image", value: "medium"},
    price: {type :"TEXT", label: "price",  key: "price"},
}

function processData(payload, config) {
    function getImage(obj, key) {
      return  Object.keys(obj).reduce((acc, cur) => {
            
            if (cur.includes(key)) {
                acc = acc + obj[cur];
            }
            return acc;
        }, "")
    }
    return payload.payload[0].data.reduce(function(acc, cur) {
            var temp = [];
            Object.keys(config).forEach(function(c) {
                    console.log(c)
                    if (c == "images") {
                        var res = getImage(cur[0][c], config[c]["value"]);
                        var ob = {
                            type: config[c]["type"],
                            value: res
                            }
                            temp.push(ob);
                        }
                        else {
                            
                            temp.push({
                               type: config[c]["type"],
                                value: cur[0][c]
                            })
                        }
                        
                    });
                acc.push(temp);
                return acc
            }, [])
    }

【问题讨论】:

  • 这里的问题到底是什么?
  • @mli 明确提及。请阅读

标签: javascript arrays json function


【解决方案1】:

编辑:哎呀,忘记配置了

尽量写出最高效简洁的代码

当然……对我来说,“高效”意味着“可以理解”——如果他们想要性能,他们应该说“性能”不是 :)。还有简洁的代码……嗯,这并不总是意味着代码质量,所以我会尽量平衡。

我的方法是至少在某种程度上统一数据,然后使用更小的函数并处理那里超级混乱的数据结构。

如果这是一个非常大的项目,并且实际上需要一个更通用的项目,那么我才会考虑使用此类数据制作任何通用的项目。通常它实际上并没有必要,只会引入很多复杂性。

const payload1 = [
  {
    data: [
      [
        {
          name: "Handbag",
          url: "https://example.com/products/handbag",
          images: {
            small: "https://example.com/products/handbag/images/small.png",
            medium: "https://example.com/products/handbag/images/medium.png",
            large: "https://example.com/products/handbag/images/large.png",
          },
          color: "black",
          price: "$50.00",
        },
      ],
      [
        {
          name: "Shoes",
          url: "https://example.com/products/shoes",
          images: {
            small: "https://example.com/products/shoes/images/small.png",
            medium: "https://example.com/products/shoes/images/medium.png",
            large: "https://example.com/products/shoes/images/large.png",
          },
          color: "red",
          price: "$35.00",
        },
      ],
    ],
  },
];

const payload2 = [
  [
    {
      product_id: "000001",
      meta: {
        en_US: {
          product_name: "Handbag",
          product_urls: ["https://example.com/products/handbag"],
          product_image_small: "https://example.com/products/handbag/images/small.png",
          product_image_medium: "https://example.com/products/handbag/images/medium.png",
          product_image_large: "https://example.com/products/handbag/images/large.png",
          product_price_cents: 5000,
          product_custom_attributes: {
            product_price_string: "$50.00",
            product_color: "black",
          },
        },
      },
    },
    {
      product_id: "000002",
      meta: {
        en_US: {
          product_name: "Shoes",
          product_urls: ["https://example.com/products/shoes"],
          product_image_small: "https://example.com/products/shoes/images/small.png",
          product_image_medium: "https://example.com/products/shoes/images/medium.png",
          product_image_large: "https://example.com/products/shoes/images/large.png",
          product_price_cents: 3500,
          product_custom_attributes: {
            product_price_string: "$35.00",
            product_color: "red",
          },
        },
      },
    },
  ],
];

// main function
const parseProducts = (data, config) => {
    const saneData = config.array ? data[0] : data[0].data;
    return saneData.map(product => {
        return [
            { type: 'TEXT',  value: getText(product, config) },   // 'Handbag'
            { type: 'URL',   value: getUrl(product, config) },    // 'https://example.com/products/handbag'
            { type: 'IMAGE', value: getImage(product, config) },  // 'https://example.com/products/handbag/images/medium.png'
            { type: 'TEXT',  value: getPrice(product, config) }   // '$50.00'
        ]
    });
};

const getText = (product, config) => {
    if (Array.isArray(product)) {
        return product[0].name;
    }
    const meta = product?.meta[config.lang];
    return meta?.product_name;
}

const getUrl = (product, config) => {
    if (Array.isArray(product)) {
        return product[0].url;
    }
    const meta = product?.meta[config.lang];
    return meta?.product_urls[0];
}

const getImage = (product, config) => {
    if (Array.isArray(product)) {
        return product[0].images.medium;
    }
    const meta = product?.meta[config.lang];
    return meta?.product_image_medium;
}

const getPrice = (product, config) => {
    if (Array.isArray(product)) {
        return product[0].price;
    }
    const meta = product?.meta[config.lang];
    return meta?.product_custom_attributes.product_price_string;
}

// Test
console.log(parseProducts(payload1, { array: 0 }));
console.log(parseProducts(payload2, { array: 1, lang: "en_US" }));

【讨论】:

  • Reducer 是很酷的工具,但...有时越简单越好。对我来说,代码的可读性和可维护性始终是最重要的。
  • TBH 这很复杂,我有时间来解决这个问题。他们本可以要求更好的方法来测试候选人在核心概念方面的能力 感谢@joel-peltonen 抽出宝贵时间。
猜你喜欢
  • 2022-06-14
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-02
相关资源
最近更新 更多