我有一个JS对象的层次结构,如下所示:
static char iobfr[512];
static void *
opnthrd(void *argp)
{
memset(iobfr, '\0', 512);
char *fname = (char *) argp;
FILE *fp = fopen(fname, "r");
if (!fp) {
pthread_exit((void *) -1);
}
int i = 0;
int c;
for (c = fgetc(fp); c != EOF; c = fgetc(fp)) {
iobfr[i++] = c;
}
iobfr[i] = '\0';
fclose(fp);
fp = NULL;
pthread_exit((void *) i);
}
static int
opnsrc(char *fnam)
{
pthread_t thrd;
void *rvp;
int rc = pthread_create(&thrd, NULL, opnthrd, fnam);
if (0 != rc) {
return (-1);
}
rc = pthread_join(thrd, &rvp);
if (0 != rc) {
return (-1);
}
if (!rvp) {
return (-1);
}
int *rvi = (int *) rvp;
return *rvi;
}
int main()
{
int ccnt = opnsrc("/var/tmp/hello.pl");
printf("%d bytes read\n", ccnt);
return 0;
}
其中Obj1引用了一个Obj2数组。如您所见,Obj1和Obj2可以具有相似的属性名称。不保证唯一性。
我想获得Obj1的JSON,我想要排除Obj2的一些属性。 我知道stringify会收到一个替换器函数或数组,而且我已经尝试过但是存在以下问题:
当我使用替换函数时,如何区分Obj1和Obj2中的属性,即使它们具有相同的名称?我的最终目标是拥有像Java toString这样的行为,每个Object都可以对其属性做出决定:
function Obj1(){
this.att1;
this.Obj2Array;
}
function Obj2(){
this.att1;
this.att2;
}
我想我错过了一个更好的解决方案。
答案 0 :(得分:2)
一个好的解决方案是使用' toJSON'功能!
就像Java调用toString的打印操作一样,在Javascript中,JSON.stringify函数调用对象' toJSON'功能。用户定义toJSON函数会更改行为,您可以选择每个对象的属性。 它是这样的:
Obj1.prototype.toJSON = function (){
return {
att1: this.att1,
obj2array: this.Obj2Array
};
}
Obj2.prototype.toJSON = function (){
return {
att2: this.att2
};
}
使用它:
var o1 = new Obj1;
// assign anything you want to o1...
JSON.stringify(o1);
答案 1 :(得分:1)
阅读你的代码我认为你想要保留Obj1的属性,只获得Obj2不存在的属性。您可以通过下一种方式使用assign方法执行此操作:
var Obj1 = {
attr1: 'foo'
};
var Obj2 = {
attr1: 'foo2',
attr2: 'bar'
};
// now, c has attr1: 'foo' (from Obj1) and attr2: 'bar' (from Obj2)
var c = Object.assign({}, Obj2, Obj1);
// and finally call json stringify with new object
JSON.stringify(c);
使用Object.assign,您可以克隆或合并对象:https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/assign