将对象数组转换为具有键值的数组

时间:2019-02-11 10:17:20

标签: javascript arrays

如何将对象数组转换为具有键和值的数组。我们确保每个对象仅包含一个值。

"values":[
    {
        "first(%)":"91.52%"
    },
    {
        "second(%)":"98.98%"
    },
    {
        "Total(%)":"95.00%"
    }
]

所需的输出:

"values":[
    "first(%)":"91.52%",
    "second(%)":"98.98%",
    "Total(%)":"95.00%",
]

4 个答案:

答案 0 :(得分:4)

您可以使用Object.assign将所有对象分配给单个对象。

(defun min-obj (list)
   (loop with min = most-positive-fixnum ; sufficient in my case
         for obj in list
         when (< obj min)
           do (setf min obj)
         finally (return min))) 

(defun range-n-p (list)
   "Check that the list is identical to min..max as a set."
   (let* ((len (length list))
          (min (min-obj list))
          ;; 0: not seen this index in list yet
          ;; 1: already seen this index in list
          (indicator (make-array len :element-type 'bit :initial-element 0)))
          (loop for obj in list for pos upfrom 0 do
               (unless (< (- obj min) len) ; I deal only with integers
                  ;; obj out of range
                  (return-from range-n-p nil))
               (if (zerop (aref indicator (- obj min)))
                  ;; obj is being seen for the 1st time; record that
                  (setf (aref indicator (- obj min)) 1)
                  ;; duplicate obj
                  (return-from range-n-p nil)))
          ;; all list elements are unique and in the right range;
          ;; injectivity + same cardinality for finite sets => surjectivity
          t))

答案 1 :(得分:2)

您可以使用.reducespread syntax将值数组中的每个对象放入新的累积对象中,如下所示:

TextAreaComponent

答案 2 :(得分:1)

JavaScript没有关联数组。但是,您可以使用对象来存储键/值。

这是一种从数组中的项中提取键/值并将其设置为使用reduce的对象的方法:

const data = {
  "values": [
    { "first(%)":"91.52%"},
    { "second(%)":"98.98%" },
    { "Total(%)":"95.00%" }
  ]
};

const result = data.values.reduce((acc, x) => {
  Object.entries(x).forEach(([key, val]) => acc[key] = val);
  return acc;
}, {});

console.log(result);

答案 3 :(得分:1)

在javascript中,您可以使用Object.assign将对象存储在键/值对中,因为JavaScript不支持关联数组。 您可以将其用作对象。

 const data = { values: 
              [{ "first(%)": "91.52%" },
               { "second(%)": "98.98%" },
               { "Total(%)": "95.00%" }] };

 const result = { values: Object.assign({}, ...data.values) };

console.log("result",result);