首页 > 解决方案 > Single array to multiple array javascript

问题描述

y have an array associative and want to save multiple arrays with only one key value like that:

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

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

标签: javascriptarrayskeyassociative

解决方案


关联数组与 JavaScript 中的对象相同,我认识的大多数人都将它们称为“对象”,而不是“关联数组”(在 JavaScript 的上下文中)。该答案还将关联数组称为对象。

您问题中的所有对象均无效。
您需要将对象文字包装在花括号中,而不是方括号中(方括号用于数组文字)。您需要将它们分配给一个变量(或将它们作为参数传递,或者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));


推荐阅读