我有一个像这样的对象:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <fstream>
using namespace std;
inline void keep_window_open() {char ch; cin>>ch;}
int main()
{
string line;
ifstream myfile("weblog.txt");
vector<string> fileLines;
//stack overflow example
if (!myfile) //test the file
{
cout << "Unable to open the file" << endl;
return 0;
}
while (getline(myfile, line))
{
fileLines.push_back(line);
//cout << line << '\n';
}
sort(fileLines.begin(), fileLines.end()); //sorting string vector
for (string &s : fileLines)
{
cout << s << " ";
ofstream newfile ("newfile.txt");
newfile << s << " ";
};
return 0;
}
我想将var obj1 = [{ first : 1, second : 2 },
{third : 3, fourth : 4},
{fifth : 5, sixth : 6}];
和keys
分成2个不同的values
,以便结果应为
arrays
我试过了:
var labels = [first, second, third, fourth, fifth, sixth];
var values = [1,2,3,4,5,6];
但结果是
var labels = [];
var values = [];
for(var key in obj1[0]){
labels.push(key);
values.push(obj1[0][key]);
}
我知道这是因为我只迭代labels = ["first","second"];
values = [1,2];
索引位置。任何人都可以建议我实现预期产出的方法。
答案 0 :(得分:4)
试试这个
var obj1 = [{ first : 1, second : 2 },
{third : 3, fourth : 4},
{fifth : 5, sixth : 6}];
var key=[];
var value=[];
obj1.forEach(function(item){
for(i in item)
{
key.push(i);
value.push(item[i]);
}
});
console.log(key);
console.log(value);
&#13;
答案 1 :(得分:2)
for (var i = 0; i < obj1.length; i++) {
for (var key in obj1[i]) {
labels.push(key);
values.push(obj1[i][key]);
}
}