javascript - 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 ]
解决方案
关联数组与 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));
推荐阅读
- python - 来自多列和字典条件的新数据框
- java - 如何在`onCreate()`中只调用一次方法并在更改活动时继续运行它
- python - 为选择列/分层列创建顶部列层
- javascript - How to assign the value to the element of an array of the object and return the updated object typscript
- html - HTML将画布放在按钮顶部
- viewcontroller - 类型“ViewController”不符合协议“CBCentralManagerDelegate”
- python-3.x - 来自 MDToolbar 的空白空白重叠 KivyMD ImageList
- amazon-web-services - 创建需要多个工人的机械土耳其人 HIT
- go - 找不到包“。” 在 .../vendor/github.com/godror/godror
- javascript - 在模板中序列化 Django 用户:Group 类型的对象不是 JSON 可序列化的