如何在JS中展平数组?

时间:2018-12-01 13:25:04

标签: javascript

我有如下数据:

const data = [{
    ratings: [ { rating: 5 } ],
    counts: [ { count: 100 } ],
}];

从某种意义上讲,我想将其展平,以摆脱数组而只拥有对象,最终结果是:

const data = {
   ratings: { rating: 5 },
   counts: { count: 100 },
};

我试图做这样的事情,但这是错误的,我认为我有点过分复杂了。

const flatten = data => {
                return data.reduce((r, { ...children }) => {
                    Object.assign(children, r);
                    if (children) Object.assign(flatten(...Object.values(children)), r);
                    return r;
                }, {})
              }

有什么想法吗?

3 个答案:

答案 0 :(得分:9)

您可以使用reduce方法创建递归函数,以将所有数组转换为对象,前提是您在这些数组中只有对象。

const data = [{ratings: [ { rating: 5 } ],counts: [ { count: 100 } ]}];

function flatten(arr) {
  return arr.reduce((r, e) => {
    const obj = Object.assign({}, e);
    for (let p in obj) {
      if (Array.isArray(obj[p])) {
        obj[p] = flatten(obj[p])
      }
    }
    return Object.assign(r, obj)
  }, {})
}

console.log(flatten(data))

答案 1 :(得分:2)

如果有可能,数据来自JSON.parse

var json = JSON.stringify( [{ratings:[{rating: 5}], counts:[{count: 100}]}] )

var result = JSON.parse(json, (k, v) => v[0] || v)

console.log( result )

答案 2 :(得分:1)

请检查:

@RequestMapping(value = "/user/getUser")
@ResponseBody
public Map<String, Object> getUser(@ModelAttribute UserRequestModel userRequest, HttpServletRequest request)
        throws Exception {
    final IContext context = contextFactory.getContext(request);
    Map<String, Object> responseMap = new HashMap<>();

    String UserID = userService.getUserID(context, userRequest.getName());

    if (UserID != null) {
        UserDetails userDetails = userService.getUserDetails(context, userID);
        ...
    }

    ...

 return responseMap;
}

------
@RequestMapping(value = "/user/Booking")
@ResponseBody
public Map<String, Object> Booking(@RequestParam("bookingRequest") String RequestAsJSON,HttpServletRequest request) throws Exception {
    Map<String, Object> responseMap = new HashMap<>();

    final IContext context = contextFactory.getContext(request);
    UserList userList = userService.getUserList(context, RequestAsJSON);
    IUserResponse userresponse = userService.createBooking(RequestAsJSON, context, userList);
    return responseMap;
}

请检查@ CodePen https://codepen.io/animatedcreativity/pen/842e17d2b9f83bc415513f937fc29be8