我有一个有数据的对象,现在我想以特定的模式转换它。
下面是我的对象
{
_groups: ["d1830f7c-12ac-4abf-bc03-f0b70e26f8f2", "d0348b51-dcaa-2227-f0ff-912b27100aee"],
_eror: "",
number: "",
seen_days: Infinity, // dont count this if this is Infinity or make add it
address: "",
status: "ACTIVE"
}
现在如果我想把它转换成下面的模式。
[
{
"field": "status",
"value": "ACTIVE",
"operator": "equal"
},
{
"field": "_groups",
"value": "d1830f7c-12ac-4abf-bc03-f0b70e26f8f2",
"operator": "equal"
},
{
"field": "_groups",
"value": "d0348b51-dcaa-2227-f0ff-912b27100aee",
"operator": "equal"
}
]
const convert = (obj) => {
const arr = [];
obj._groups.forEach((el) => {
arr.push({
field: "_groups",
value: el,
operator: "equal",
});
});
console.log(obj)
var key = Object.keys(obj);
var value = obj[key];
arr.push({
field: value,
value: obj.status,
operator: "equal",
});
return arr;
}
目前正在尝试此功能,但没有按预期工作。
给你一条线。
const converted = Object.keys(your_object)
.filter(v => !!your_object[v] )
.map(v => ({ field: v, value: JSON.stringify( your_object[v] ) , operator: "equal" })
const x = {
_groups: ["d1830f7c-12ac-4abf-bc03-f0b70e26f8f2", "d0348b51-dcaa-2227-f0ff-912b27100aee"],
_eror: "",
number: "",
seen_days: Infinity, // dont count this if this is Infinity or make add it
address: "",
status: "ACTIVE"
}
const result = []
createObj = (item,value) => {
const temp = { }
temp["field"] = item
temp["value"] = value
temp["operator"] = "equal"
result.push(temp)
}
Object.keys(x).forEach(item => {
if(x[item] && x[item] !== Infinity){
if(Array.isArray(x[item])){
x[item].forEach(record => {
createObj(item, record)
})
} else {
createObj(item, x[item])
}
}
})
console.log(result)