Reputation: 75
I need to convert object to several arrays, without duplicate keys, if there is a key that consist "user_" or "city_", create new array. The first three props/keys always are the same.
for example
const test = {
"mainPoint": "user1",
"create_Date": "2018-04-23 16:51:10",
"delete_Date": "2018-04-23 16:50",
"user_one": 4,
"user_two": 4,
"city_one": bs,
"city_two": mi
}
to this:
['user1','2018-04-23 16:51:10','2018-04-23 16:50','user_one',4]
['user1','2018-04-23 16:51:10','2018-04-23 16:50','user_two',4]
['user1','2018-04-23 16:51:10','2018-04-23 16:50','city_one','bs']
['user1','2018-04-23 16:51:10','2018-04-23 16:50','city_two','mi']
This is my code
let tempArr = [];
for(let key in test){
tempArr = [];
if(key.indexOf("user_") !== -1 || key.indexOf("city_") !== -1){
tempArr.push(test['mainPoint']);
tempArr.push(test['create_Date']);
tempArr.push(test['delete_Date']);
tempArr.push(key);
tempArr.push(test[key]);
}
console.log(tempParams);
}
thanks for any help!
Upvotes: 0
Views: 77
Reputation: 67
Please find the working code below. In your code, you have not added tempArr into tempArrs.
Erros in code:
1. "city_one": and "city_two": values are not double quotes.
2. remove the const from test declaration
3. remove the let from array declaration
4. console.log should be outside.
test = {
"mainPoint": "user1",
"create_Date": "2018-04-23 16:51:10",
"delete_Date": "2018-04-23 16:50",
"user_one": 4,
"user_two": 4,
"city_one": "bs",
"city_two": "mi"
}
tempArr = [];
tempArrs = [];
for(let key in test){
tempArr = [];
if(key.indexOf("user_") !== -1 || key.indexOf("city_") !== -1){
tempArr.push(test['mainPoint']);
tempArr.push(test['create_Date']);
tempArr.push(test['delete_Date']);
tempArr.push(key);
tempArr.push(test[key]);
tempArrs.push(tempArr);
}
}
console.log(tempArrs);
Upvotes: 1
Reputation: 751
Test with following code:
{
const test = {
"mainPoint": "user1",
"create_Date": "2018-04-23 16:51:10",
"delete_Date": "2018-04-23 16:50",
"user_one": 4,
"user_two": 4,
"city_one": "bs",
"city_two": "mi"
};
let static = [], dynamic = [], final = [];
for ( const [ key, value ] of Object.entries( test ) ) {
if ( !key.match( /user_|city_/gi ) ) static.push( value );
else dynamic.push( [ key, value ] );
}
for ( const item of dynamic ) {
final.push( [ ...static, ...item ] );
}
console.log( final );
}
Upvotes: 1
Reputation: 13953
You were just not using tempParams
to group each array
const test = {
"mainPoint": "user1",
"create_Date": "2018-04-23 16:51:10",
"delete_Date": "2018-04-23 16:50",
"user_one": 4,
"user_two": 4,
"city_one": "bs",
"city_two": "mi"
};
let tempParams = [];
for (let key in test) {
tempArr = [];
if (key.indexOf("user_") !== -1 || key.indexOf("city_") !== -1) {
tempArr.push(test['mainPoint']);
tempArr.push(test['create_Date']);
tempArr.push(test['delete_Date']);
tempArr.push(key);
tempArr.push(test[key]);
tempParams.push(tempArr);
}
}
console.log(JSON.stringify(tempParams));
Upvotes: 1