我有一个带有键值对的对象,其值作为元素数组。
{
status: ["new", "old"],
place: ["york", "blah"]
}
我正尝试将其转换为键值对的多个数组对象,如下所示。
{
"newObj1": [
{ "status": "new" },
{ "status": "old" }],
"newObj2": [
{ "place": "york" },
{ "place": "blah" }]
}
有什么办法可以实现上述结构?我已经尝试了使用数组归约方法的几种方法,但是没有给出期望的输出。
let value= {
status: ["new", "old"],
place: ["york", "blah"]
}
Object.keys(value).map((key) => [key, value[key]]);
答案 0 :(得分:1)
您可以做这样的事情
from pypoman import compute_polytope_vertices
File "C:\Users\omidi\PycharmProjects\pypoman\venv\lib\site-packages\pypoman\__init__.py", line 27, in <module>
from .lp import solve_lp
File "C:\Users\omidi\PycharmProjects\pypoman\venv\lib\site-packages\pypoman\lp.py", line 21, in <module>
import cvxopt
File "C:\Users\omidi\PycharmProjects\pypoman\venv\lib\site-packages\cvxopt\__init__.py", line 50, in <module>
import cvxopt.base
ImportError: DLL load failed: The specified module could not be found.
答案 1 :(得分:0)
const data = {
status: ["new", "old"],
place: ["york", "blah"]
};
let result = Object.fromEntries( Object.entries(data).map( ([key, [first, second]], index) => {
return [ `newObj${index}`, [ { [key]: first }, { [key]: second } ] ];
} ) );
console.log(result);
答案 2 :(得分:0)
以下是使用Array.reduce()
的解决方案:
const value = {
status: ["new", "old"],
place: ["york", "blah"]
};
const result = Object.keys(value).reduce((acc, key, i) => {
acc["newObj" + (i + 1)] = value[key].map(k => ({ [key]: k }));
return acc;
}, {});
console.log(result);
答案 3 :(得分:0)
这是我完成任务的方式。
let source = {
status: ["new", "old"],
place: ["york", "blah"]
};
let destination = {}; // make room for the destinoation object
Object.keys(source).forEach((key, index) => {
let obj = "newObj" + (index + 1); // assume all objects are named "newObj1,2,3,etc"
if (!destination[obj]) { // check if the object exists already
// if not, then crate an empty array first
destination[obj] = [];
}
// loop through all items in the source element array
source[key].forEach(value => {
// create an object from the array element
let subObj = {};
subObj[key] = value;
// push that object to the destination
destination[obj].push(subObj);
});
});
console.log(destination);
答案 4 :(得分:0)
这是在.reduce
内使用.reduce
的惯用解决方案:
Object.entries(data)
.reduce((result, [key, value], index) => !(result['newObj' + (index + 1)] = value
.reduce((arr, text) => !arr
.push({ [key]: text }) || arr, [])) || result, {});
这是一个实时示例:
const data = {
status: ['new', 'old'],
place: ['york', 'blah']
};
const result = Object.entries(data)
.reduce((result, [key, value], index) => !(result['newObj' + (index + 1)] = value
.reduce((arr, text) => !arr
.push({ [key]: text }) || arr, [])) || result, {});
console.log(result);
/*
{
newObj1: [
{ status: 'new' },
{ status: 'old' }
],
newObj2: [
{ place: 'york' },
{ place: 'blah' }
]
}
*/
答案 5 :(得分:0)
对于那些不了解map和reduce的人来说,这是一个非常幼稚的解决方案,但它会起作用:
// Get schools as a Collection
$schools = collect($api->schools);
// Pluck out all the 'id' key values
$info = $schools->pluck('id');