单数组到多数组javascript

Single array to multiple array javascript

y 有一个关联数组,想保存多个只有一个键值的数组:

[
  key1: value1,
  key2: value2,
  key3: value3
]

[ key1: value1 ]
[ key2: value2 ]
[ key3: value3 ]

Associative Arrays are the same as Objects 在 JavaScript 中,我认识的大多数人都提到它们 "Objects",而不是 "Associative Arrays"(在 JavaScript 的上下文中)。 该答案还将关联数组称为对象。

None 个问题中的对象是有效的。
您需要将对象文字包裹在花括号中,而不是方括号中(方括号用于数组文字)。 您需要将它们分配给一个变量(或将它们作为参数传递,或者在它们前面有一个 return 关键字等)。

我假设您想要变成多个对象的对象是您的第一个示例,而第二个示例是完成后的样子。 这是您的示例,已重写以符合该假设。

// assign it to a variable
var firstExample = {
  key1: 'value1',   // dunno if value1, 2, or 3 are strings, but stringifying them works for an example
  key2: 'value2',
  key3: 'value3'
};

var secondExample = [   // I assume you want an array of objects, each with a single key/value pair.
    { key1: 'value1' },
    { key2: 'value2' },
    { key3: 'value3' },
];

也就是说,我能想到的最简单的方法是获取对象的键,然后遍历它们并将它们映射到单个对象。

var firstExample = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3'
};

var secondExample = [
    { key1: 'value1' },
    { key2: 'value2' },
    { key3: 'value3' },
];

// ES6 syntax
const arrayOfObjects = Object.keys(firstExample).map(key => ( { [key]: firstExample[key] } ));

console.log('Array of objects', arrayOfObjects);
console.log('arrayOfObjects is equivalent to secondExample:', JSON.stringify(arrayOfObjects) === JSON.stringify(secondExample));

// ES5 syntax
var es5 = Object.keys(firstExample).map(function (key) {
    var o = {};
    o[key] = firstExample[key];
    return o;
});

console.log('ES5-syntax array of objects', es5);
console.log('es5 is equivalent to secondExample:', JSON.stringify(es5) === JSON.stringify(secondExample));