Как получить доступ к ключу во вложенном массиве, используя функцию карты? - PullRequest
0 голосов
/ 23 мая 2019

У меня есть вложенный массив:

var arr = [
{
"id": 18,
"published": 1,
"include_inproject": 1,
"created_at": "2017-09-21 11:27:46",
"updated_at": "2018-06-18 15:35:38",
"name": "1-1 Benban Arinna Solar PV II",
"status_id": 15,
"capacity": 20,
"technology_id": 2,
"commercial_operations": "2019-03-31 00:00:00",
"commercial_operations_estemated": "Q1 2019",
"commercial_operations_end": "",
"commercial_operations_end_estemated": "",
"start_construction": "2018-06-18 00:00:00",
"project_id": 530,
"start_construction_estimated": "June 2018",
"capacity_low": "",
"capacity_high": "",
"technology": "Photovoltaic (PV)",
"country": "Egypt",
"region": "North Africa",
"fuels": "Solar",
"status": "Planned",
"ownership_type": "IPP",
"Units": [
  {
    "id": 1,
    "published": 1,
    "include_inproject": 1,
    "created_at": "2017-09-21 12:14:47",
    "updated_at": "2017-09-21 12:14:47",
    "name": "1-1 Benban Arinna Solar PV II",
    "grid_connection": "On-grid",
    "status_id": 14,
    "capacity": 20,
    "technology_id": 1,
    "commercial_operations": "1959-01-01 00:00:00",
    "commercial_operations_estemated": "1959",
    "commercial_operations_end": null,
    "commercial_operations_end_estemated": "",
    "start_construction": null,
    "project_id": 470,
    "start_construction_estimated": "",
    "capacity_low": null,
    "capacity_high": null
      }
    ]
}
]

Массив содержит несколько элементов, подобных приведенному выше.

Я хочу получить доступ к определенным ключам в массиве и могу использовать функцию .map:

var cols1 = arr.map(function(obj){
return obj["name"]   
})

Это вернет все значения под ключом «Имя» во всем массиве первого уровня.

Каждый элемент массива имеет дочерний массив с именем «Units», и я также хочу получить доступ к ключу в этом массиве, но у меня возникают проблемы при этом. Я знаю, как перейти к нему за пределами карты:

обр [0] .Units [0] .name

Однако при этом будет получен только первый экземпляр значения ключа, я хочу отобразить весь массив и получить все значения в массиве «Units».

Я пытался:

arr[0].Units.map(function(obj){
return obj[name]
})

Но появляется ошибка: не удается вызвать метод "map" из неопределенного

Я думаю, что проблема заключается в отображении подмассива "Units", когда они не находятся в одном массиве для начала. Я просто не знаю, как это исправить. Любая помощь будет здорово!

Ответы [ 4 ]

0 голосов
/ 23 мая 2019

В качестве альтернативы используйте библиотеку JMESPath для выполнения запросов к вложенным объектам JSON:

var arr = [
	{
        "id": 18,
        "published": 1,
        "include_inproject": 1,
        "created_at": "2017-09-21 11:27:46",
        "updated_at": "2018-06-18 15:35:38",
        "name": "1-1 Benban Arinna Solar PV II",
        "status_id": 15,
        "capacity": 20,
        "technology_id": 2,
        "commercial_operations": "2019-03-31 00:00:00",
        "commercial_operations_estemated": "Q1 2019",
        "commercial_operations_end": "",
        "commercial_operations_end_estemated": "",
        "start_construction": "2018-06-18 00:00:00",
        "project_id": 530,
        "start_construction_estimated": "June 2018",
        "capacity_low": "",
        "capacity_high": "",
        "technology": "Photovoltaic (PV)",
        "country": "Egypt",
        "region": "North Africa",
        "fuels": "Solar",
        "status": "Planned",
        "ownership_type": "IPP",
        "Units": [
            {
                "id": 1,
                "published": 1,
                "include_inproject": 1,
                "created_at": "2017-09-21 12:14:47",
                "updated_at": "2017-09-21 12:14:47",
                "name": "1-1 Benban Arinna Solar PV II",
                "grid_connection": "On-grid",
                "status_id": 14,
                "capacity": 20,
                "technology_id": 1,
                "commercial_operations": "1959-01-01 00:00:00",
                "commercial_operations_estemated": "1959",
                "commercial_operations_end": null,
                "commercial_operations_end_estemated": "",
                "start_construction": null,
                "project_id": 470,
                "start_construction_estimated": "",
                "capacity_low": null,
                "capacity_high": null
            },
            {
                "id": 2,
                "published": 1,
                "include_inproject": 1,
                "created_at": "2018-09-21 12:14:47",
                "updated_at": "2018-09-21 12:14:47",
                "name": "SOME-OTHER-NAME",
                "grid_connection": "On-grid",
                "status_id": 14,
                "capacity": 20,
                "technology_id": 1,
                "commercial_operations": "1959-01-01 00:00:00",
                "commercial_operations_estemated": "1959",
                "commercial_operations_end": null,
                "commercial_operations_end_estemated": "",
                "start_construction": null,
                "project_id": 470,
                "start_construction_estimated": "",
                "capacity_low": null,
                "capacity_high": null
            
            }
        ]
    }
];

// Execute JMESPath query on JSON arr
var result = jmespath.search(arr, "[0].[name, Units[*].name]");
console.log(result);
<!-- Javascript implementation of JMESPATH -->
<script>
/** jmespath.js minified (https://github.com/jmespath/jmespath.js)*/
!function(e){"use strict";function j(e){return null!==e&&"[object Array]"===Object.prototype.toString.call(e)}function N(e){return null!==e&&"[object Object]"===Object.prototype.toString.call(e)}function O(e,t){if(e===t)return!0;if(Object.prototype.toString.call(e)!==Object.prototype.toString.call(t))return!1;if(!0===j(e)){if(e.length!==t.length)return!1;for(var r=0;r<e.length;r++)if(!1===O(e[r],t[r]))return!1;return!0}if(!0!==N(e))return!1;var n={};for(var i in e)if(hasOwnProperty.call(e,i)){if(!1===O(e[i],t[i]))return!1;n[i]=!0}for(var s in t)if(hasOwnProperty.call(t,s)&&!0!==n[s])return!1;return!0}function P(e){if(""===e||!1===e||null===e)return!0;if(j(e)&&0===e.length)return!0;if(N(e)){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0}return!1}var a;a="function"==typeof String.prototype.trimLeft?function(e){return e.trimLeft()}:function(e){return e.match(/^\s*(.*)/)[1]};var c=0,s=1,h=2,u=3,t=4,r=6,o=8,l=9,_={0:"number",1:"any",2:"string",3:"array",4:"object",5:"boolean",6:"expression",7:"null",8:"Array<number>",9:"Array<string>"},i="EOF",f="UnquotedIdentifier",p="QuotedIdentifier",v="Rbracket",d="Rparen",y="Comma",g="Colon",m="Rbrace",k="Number",M="Current",I="Expref",L="Pipe",x="Or",w="And",R="EQ",A="GT",F="LT",H="GTE",C="LTE",B="NE",J="Flatten",S="Star",b="Filter",E="Dot",T="Not",U="Lbrace",z="Lbracket",D="Lparen",K="Literal",Q={".":E,"*":S,",":y,":":g,"{":U,"}":m,"]":v,"(":D,")":d,"@":M},V={"<":!0,">":!0,"=":!0,"!":!0},q={" ":!0,"\t":!0,"\n":!0};function W(e){return"0"<=e&&e<="9"||"-"===e}function n(){}n.prototype={tokenize:function(e){var t,r,n,i,s=[];for(this._current=0;this._current<e.length;)if("a"<=(i=e[this._current])&&i<="z"||"A"<=i&&i<="Z"||"_"===i)t=this._current,r=this._consumeUnquotedIdentifier(e),s.push({type:f,value:r,start:t});else if(void 0!==Q[e[this._current]])s.push({type:Q[e[this._current]],value:e[this._current],start:this._current}),this._current++;else if(W(e[this._current]))n=this._consumeNumber(e),s.push(n);else if("["===e[this._current])n=this._consumeLBracket(e),s.push(n);else if('"'===e[this._current])t=this._current,r=this._consumeQuotedIdentifier(e),s.push({type:p,value:r,start:t});else if("'"===e[this._current])t=this._current,r=this._consumeRawStringLiteral(e),s.push({type:K,value:r,start:t});else if("`"===e[this._current]){t=this._current;var a=this._consumeLiteral(e);s.push({type:K,value:a,start:t})}else if(void 0!==V[e[this._current]])s.push(this._consumeOperator(e));else if(void 0!==q[e[this._current]])this._current++;else if("&"===e[this._current])t=this._current,this._current++,"&"===e[this._current]?(this._current++,s.push({type:w,value:"&&",start:t})):s.push({type:I,value:"&",start:t});else{if("|"!==e[this._current]){var u=new Error("Unknown character:"+e[this._current]);throw u.name="LexerError",u}t=this._current,this._current++,"|"===e[this._current]?(this._current++,s.push({type:x,value:"||",start:t})):s.push({type:L,value:"|",start:t})}return s},_consumeUnquotedIdentifier:function(e){var t,r=this._current;for(this._current++;this._current<e.length&&("a"<=(t=e[this._current])&&t<="z"||"A"<=t&&t<="Z"||"0"<=t&&t<="9"||"_"===t);)this._current++;return e.slice(r,this._current)},_consumeQuotedIdentifier:function(e){var t=this._current;this._current++;for(var r=e.length;'"'!==e[this._current]&&this._current<r;){var n=this._current;"\\"!==e[n]||"\\"!==e[n+1]&&'"'!==e[n+1]?n++:n+=2,this._current=n}return this._current++,JSON.parse(e.slice(t,this._current))},_consumeRawStringLiteral:function(e){var t=this._current;this._current++;for(var r=e.length;"'"!==e[this._current]&&this._current<r;){var n=this._current;"\\"!==e[n]||"\\"!==e[n+1]&&"'"!==e[n+1]?n++:n+=2,this._current=n}return this._current++,e.slice(t+1,this._current-1).replace("\\'","'")},_consumeNumber:function(e){var t=this._current;this._current++;for(var r=e.length;W(e[this._current])&&this._current<r;)this._current++;var n=parseInt(e.slice(t,this._current));return{type:k,value:n,start:t}},_consumeLBracket:function(e){var t=this._current;return this._current++,"?"===e[this._current]?(this._current++,{type:b,value:"[?",start:t}):"]"===e[this._current]?(this._current++,{type:J,value:"[]",start:t}):{type:z,value:"[",start:t}},_consumeOperator:function(e){var t=this._current,r=e[t];return this._current++,"!"===r?"="===e[this._current]?(this._current++,{type:B,value:"!=",start:t}):{type:T,value:"!",start:t}:"<"===r?"="===e[this._current]?(this._current++,{type:C,value:"<=",start:t}):{type:F,value:"<",start:t}:">"===r?"="===e[this._current]?(this._current++,{type:H,value:">=",start:t}):{type:A,value:">",start:t}:"="===r&&"="===e[this._current]?(this._current++,{type:R,value:"==",start:t}):void 0},_consumeLiteral:function(e){this._current++;for(var t,r=this._current,n=e.length;"`"!==e[this._current]&&this._current<n;){var i=this._current;"\\"!==e[i]||"\\"!==e[i+1]&&"`"!==e[i+1]?i++:i+=2,this._current=i}var s=a(e.slice(r,this._current));return s=s.replace("\\`","`"),t=this._looksLikeJSON(s)?JSON.parse(s):JSON.parse('"'+s+'"'),this._current++,t},_looksLikeJSON:function(e){if(""===e)return!1;if(0<='[{"'.indexOf(e[0]))return!0;if(0<=["true","false","null"].indexOf(e))return!0;if(!(0<="-0123456789".indexOf(e[0])))return!1;try{return JSON.parse(e),!0}catch(e){return!1}}};var G={};function Z(){}function X(e){this.runtime=e}function Y(e){this._interpreter=e,this.functionTable={abs:{_func:this._functionAbs,_signature:[{types:[c]}]},avg:{_func:this._functionAvg,_signature:[{types:[o]}]},ceil:{_func:this._functionCeil,_signature:[{types:[c]}]},contains:{_func:this._functionContains,_signature:[{types:[h,u]},{types:[s]}]},ends_with:{_func:this._functionEndsWith,_signature:[{types:[h]},{types:[h]}]},floor:{_func:this._functionFloor,_signature:[{types:[c]}]},length:{_func:this._functionLength,_signature:[{types:[h,u,t]}]},map:{_func:this._functionMap,_signature:[{types:[r]},{types:[u]}]},max:{_func:this._functionMax,_signature:[{types:[o,l]}]},merge:{_func:this._functionMerge,_signature:[{types:[t],variadic:!0}]},max_by:{_func:this._functionMaxBy,_signature:[{types:[u]},{types:[r]}]},sum:{_func:this._functionSum,_signature:[{types:[o]}]},starts_with:{_func:this._functionStartsWith,_signature:[{types:[h]},{types:[h]}]},min:{_func:this._functionMin,_signature:[{types:[o,l]}]},min_by:{_func:this._functionMinBy,_signature:[{types:[u]},{types:[r]}]},type:{_func:this._functionType,_signature:[{types:[s]}]},keys:{_func:this._functionKeys,_signature:[{types:[t]}]},values:{_func:this._functionValues,_signature:[{types:[t]}]},sort:{_func:this._functionSort,_signature:[{types:[l,o]}]},sort_by:{_func:this._functionSortBy,_signature:[{types:[u]},{types:[r]}]},join:{_func:this._functionJoin,_signature:[{types:[h]},{types:[l]}]},reverse:{_func:this._functionReverse,_signature:[{types:[h,u]}]},to_array:{_func:this._functionToArray,_signature:[{types:[s]}]},to_string:{_func:this._functionToString,_signature:[{types:[s]}]},to_number:{_func:this._functionToNumber,_signature:[{types:[s]}]},not_null:{_func:this._functionNotNull,_signature:[{types:[s],variadic:!0}]}}}G[i]=0,G[f]=0,G[p]=0,G[v]=0,G[d]=0,G[y]=0,G[m]=0,G[k]=0,G[M]=0,G[I]=0,G[L]=1,G.Or=2,G[w]=3,G.EQ=5,G.GT=5,G.LT=5,G[H]=5,G[C]=5,G.NE=5,G[J]=9,G[S]=20,G[b]=21,G[E]=40,G[T]=45,G[U]=50,G[z]=55,G[D]=60,Z.prototype={parse:function(e){this._loadTokens(e),this.index=0;var t=this.expression(0);if(this._lookahead(0)===i)return t;var r=this._lookaheadToken(0),n=new Error("Unexpected token type: "+r.type+", value: "+r.value);throw n.name="ParserError",n},_loadTokens:function(e){var t=(new n).tokenize(e);t.push({type:i,value:"",start:e.length}),this.tokens=t},expression:function(e){var t=this._lookaheadToken(0);this._advance();for(var r=this.nud(t),n=this._lookahead(0);e<G[n];)this._advance(),r=this.led(n,r),n=this._lookahead(0);return r},_lookahead:function(e){return this.tokens[this.index+e].type},_lookaheadToken:function(e){return this.tokens[this.index+e]},_advance:function(){this.index++},nud:function(e){var t,r;switch(e.type){case K:return{type:"Literal",value:e.value};case f:return{type:"Field",name:e.value};case p:var n={type:"Field",name:e.value};if(this._lookahead(0)===D)throw new Error("Quoted identifier not allowed for function names.");return n;case T:return{type:"NotExpression",children:[t=this.expression(G.Not)]};case S:return t=null,{type:"ValueProjection",children:[{type:"Identity"},t=this._lookahead(0)===v?{type:"Identity"}:this._parseProjectionRHS(G.Star)]};case b:return this.led(e.type,{type:"Identity"});case U:return this._parseMultiselectHash();case J:return{type:"Projection",children:[{type:J,children:[{type:"Identity"}]},t=this._parseProjectionRHS(G.Flatten)]};case z:return this._lookahead(0)===k||this._lookahead(0)===g?(t=this._parseIndexExpression(),this._projectIfSlice({type:"Identity"},t)):this._lookahead(0)===S&&this._lookahead(1)===v?(this._advance(),this._advance(),{type:"Projection",children:[{type:"Identity"},t=this._parseProjectionRHS(G.Star)]}):this._parseMultiselectList();case M:return{type:M};case I:return{type:"ExpressionReference",children:[r=this.expression(G.Expref)]};case D:for(var i=[];this._lookahead(0)!==d;)this._lookahead(0)===M?(r={type:M},this._advance()):r=this.expression(0),i.push(r);return this._match(d),i[0];default:this._errorToken(e)}},led:function(e,t){var r;switch(e){case E:var n=G.Dot;return this._lookahead(0)!==S?{type:"Subexpression",children:[t,r=this._parseDotRHS(n)]}:(this._advance(),{type:"ValueProjection",children:[t,r=this._parseProjectionRHS(n)]});case L:return r=this.expression(G.Pipe),{type:L,children:[t,r]};case x:return{type:"OrExpression",children:[t,r=this.expression(G.Or)]};case w:return{type:"AndExpression",children:[t,r=this.expression(G.And)]};case D:for(var i,s=t.name,a=[];this._lookahead(0)!==d;)this._lookahead(0)===M?(i={type:M},this._advance()):i=this.expression(0),this._lookahead(0)===y&&this._match(y),a.push(i);return this._match(d),{type:"Function",name:s,children:a};case b:var u=this.expression(0);return this._match(v),{type:"FilterProjection",children:[t,r=this._lookahead(0)===J?{type:"Identity"}:this._parseProjectionRHS(G.Filter),u]};case J:return{type:"Projection",children:[{type:J,children:[t]},this._parseProjectionRHS(G.Flatten)]};case R:case B:case A:case H:case F:case C:return this._parseComparator(t,e);case z:var o=this._lookaheadToken(0);return o.type===k||o.type===g?(r=this._parseIndexExpression(),this._projectIfSlice(t,r)):(this._match(S),this._match(v),{type:"Projection",children:[t,r=this._parseProjectionRHS(G.Star)]});default:this._errorToken(this._lookaheadToken(0))}},_match:function(e){if(this._lookahead(0)!==e){var t=this._lookaheadToken(0),r=new Error("Expected "+e+", got: "+t.type);throw r.name="ParserError",r}this._advance()},_errorToken:function(e){var t=new Error("Invalid token ("+e.type+'): "'+e.value+'"');throw t.name="ParserError",t},_parseIndexExpression:function(){if(this._lookahead(0)===g||this._lookahead(1)===g)return this._parseSliceExpression();var e={type:"Index",value:this._lookaheadToken(0).value};return this._advance(),this._match(v),e},_projectIfSlice:function(e,t){var r={type:"IndexExpression",children:[e,t]};return"Slice"===t.type?{type:"Projection",children:[r,this._parseProjectionRHS(G.Star)]}:r},_parseSliceExpression:function(){for(var e=[null,null,null],t=0,r=this._lookahead(0);r!==v&&t<3;){if(r===g)t++,this._advance();else{if(r!==k){var n=this._lookahead(0),i=new Error("Syntax error, unexpected token: "+n.value+"("+n.type+")");throw i.name="Parsererror",i}e[t]=this._lookaheadToken(0).value,this._advance()}r=this._lookahead(0)}return this._match(v),{type:"Slice",children:e}},_parseComparator:function(e,t){return{type:"Comparator",name:t,children:[e,this.expression(G[t])]}},_parseDotRHS:function(e){var t=this._lookahead(0);return 0<=[f,p,S].indexOf(t)?this.expression(e):t===z?(this._match(z),this._parseMultiselectList()):t===U?(this._match(U),this._parseMultiselectHash()):void 0},_parseProjectionRHS:function(e){var t;if(G[this._lookahead(0)]<10)t={type:"Identity"};else if(this._lookahead(0)===z)t=this.expression(e);else if(this._lookahead(0)===b)t=this.expression(e);else{if(this._lookahead(0)!==E){var r=this._lookaheadToken(0),n=new Error("Sytanx error, unexpected token: "+r.value+"("+r.type+")");throw n.name="ParserError",n}this._match(E),t=this._parseDotRHS(e)}return t},_parseMultiselectList:function(){for(var e=[];this._lookahead(0)!==v;){var t=this.expression(0);if(e.push(t),this._lookahead(0)===y&&(this._match(y),this._lookahead(0)===v))throw new Error("Unexpected token Rbracket")}return this._match(v),{type:"MultiSelectList",children:e}},_parseMultiselectHash:function(){for(var e,t,r,n=[],i=[f,p];;){if(e=this._lookaheadToken(0),i.indexOf(e.type)<0)throw new Error("Expecting an identifier token, got: "+e.type);if(t=e.value,this._advance(),this._match(g),r={type:"KeyValuePair",name:t,value:this.expression(0)},n.push(r),this._lookahead(0)===y)this._match(y);else if(this._lookahead(0)===m){this._match(m);break}}return{type:"MultiSelectHash",children:n}}},X.prototype={search:function(e,t){return this.visit(e,t)},visit:function(e,t){var r,n,i,s,a,u,o,c,h;switch(e.type){case"Field":return null!==t&&N(t)?void 0===(u=t[e.name])?null:u:null;case"Subexpression":for(i=this.visit(e.children[0],t),h=1;h<e.children.length;h++)if(null===(i=this.visit(e.children[1],i)))return null;return i;case"IndexExpression":return o=this.visit(e.children[0],t),this.visit(e.children[1],o);case"Index":if(!j(t))return null;var l=e.value;return l<0&&(l=t.length+l),void 0===(i=t[l])&&(i=null),i;case"Slice":if(!j(t))return null;var _=e.children.slice(0),f=this.computeSliceParams(t.length,_),p=f[0],v=f[1],d=f[2];if(i=[],0<d)for(h=p;h<v;h+=d)i.push(t[h]);else for(h=p;v<h;h+=d)i.push(t[h]);return i;case"Projection":var y=this.visit(e.children[0],t);if(!j(y))return null;for(c=[],h=0;h<y.length;h++)null!==(n=this.visit(e.children[1],y[h]))&&c.push(n);return c;case"ValueProjection":if(!N(y=this.visit(e.children[0],t)))return null;c=[];var g=function(e){for(var t=Object.keys(e),r=[],n=0;n<t.length;n++)r.push(e[t[n]]);return r}(y);for(h=0;h<g.length;h++)null!==(n=this.visit(e.children[1],g[h]))&&c.push(n);return c;case"FilterProjection":if(!j(y=this.visit(e.children[0],t)))return null;var m=[],k=[];for(h=0;h<y.length;h++)P(r=this.visit(e.children[2],y[h]))||m.push(y[h]);for(var x=0;x<m.length;x++)null!==(n=this.visit(e.children[1],m[x]))&&k.push(n);return k;case"Comparator":switch(s=this.visit(e.children[0],t),a=this.visit(e.children[1],t),e.name){case R:i=O(s,a);break;case B:i=!O(s,a);break;case A:i=a<s;break;case H:i=a<=s;break;case F:i=s<a;break;case C:i=s<=a;break;default:throw new Error("Unknown comparator: "+e.name)}return i;case J:var w=this.visit(e.children[0],t);if(!j(w))return null;var S=[];for(h=0;h<w.length;h++)j(n=w[h])?S.push.apply(S,n):S.push(n);return S;case"Identity":return t;case"MultiSelectList":if(null===t)return null;for(c=[],h=0;h<e.children.length;h++)c.push(this.visit(e.children[h],t));return c;case"MultiSelectHash":if(null===t)return null;var b;for(c={},h=0;h<e.children.length;h++)c[(b=e.children[h]).name]=this.visit(b.value,t);return c;case"OrExpression":return P(r=this.visit(e.children[0],t))&&(r=this.visit(e.children[1],t)),r;case"AndExpression":return!0===P(s=this.visit(e.children[0],t))?s:this.visit(e.children[1],t);case"NotExpression":return P(s=this.visit(e.children[0],t));case"Literal":return e.value;case L:return o=this.visit(e.children[0],t),this.visit(e.children[1],o);case M:return t;case"Function":var E=[];for(h=0;h<e.children.length;h++)E.push(this.visit(e.children[h],t));return this.runtime.callFunction(e.name,E);case"ExpressionReference":var T=e.children[0];return T.jmespathType=I,T;default:throw new Error("Unknown node type: "+e.type)}},computeSliceParams:function(e,t){var r=t[0],n=t[1],i=t[2],s=[null,null,null];if(null===i)i=1;else if(0===i){var a=new Error("Invalid slice, step cannot be 0");throw a.name="RuntimeError",a}var u=i<0;return r=null===r?u?e-1:0:this.capSliceRange(e,r,i),n=null===n?u?-1:e:this.capSliceRange(e,n,i),s[0]=r,s[1]=n,s[2]=i,s},capSliceRange:function(e,t,r){return t<0?(t+=e)<0&&(t=r<0?-1:0):e<=t&&(t=r<0?e-1:e),t}},Y.prototype={callFunction:function(e,t){var r=this.functionTable[e];if(void 0===r)throw new Error("Unknown function: "+e+"()");return this._validateArgs(e,t,r._signature),r._func.call(this,t)},_validateArgs:function(e,t,r){var n,i,s,a;if(r[r.length-1].variadic){if(t.length<r.length)throw n=1===r.length?" argument":" arguments",new Error("ArgumentError: "+e+"() takes at least"+r.length+n+" but received "+t.length)}else if(t.length!==r.length)throw n=1===r.length?" argument":" arguments",new Error("ArgumentError: "+e+"() takes "+r.length+n+" but received "+t.length);for(var u=0;u<r.length;u++){a=!1,i=r[u].types,s=this._getTypeName(t[u]);for(var o=0;o<i.length;o++)if(this._typeMatches(s,i[o],t[u])){a=!0;break}if(!a){var c=i.map(function(e){return _[e]}).join(",");throw new Error("TypeError: "+e+"() expected argument "+(u+1)+" to be type "+c+" but received type "+_[s]+" instead.")}}},_typeMatches:function(e,t,r){if(t===s)return!0;if(t!==l&&t!==o&&t!==u)return e===t;if(t===u)return e===u;if(e===u){var n;t===o?n=c:t===l&&(n=h);for(var i=0;i<r.length;i++)if(!this._typeMatches(this._getTypeName(r[i]),n,r[i]))return!1;return!0}},_getTypeName:function(e){switch(Object.prototype.toString.call(e)){case"[object String]":return h;case"[object Number]":return c;case"[object Array]":return u;case"[object Boolean]":return 5;case"[object Null]":return 7;case"[object Object]":return e.jmespathType===I?r:t}},_functionStartsWith:function(e){return 0===e[0].lastIndexOf(e[1])},_functionEndsWith:function(e){var t=e[0],r=e[1];return-1!==t.indexOf(r,t.length-r.length)},_functionReverse:function(e){if(this._getTypeName(e[0])===h){for(var t=e[0],r="",n=t.length-1;0<=n;n--)r+=t[n];return r}var i=e[0].slice(0);return i.reverse(),i},_functionAbs:function(e){return Math.abs(e[0])},_functionCeil:function(e){return Math.ceil(e[0])},_functionAvg:function(e){for(var t=0,r=e[0],n=0;n<r.length;n++)t+=r[n];return t/r.length},_functionContains:function(e){return 0<=e[0].indexOf(e[1])},_functionFloor:function(e){return Math.floor(e[0])},_functionLength:function(e){return N(e[0])?Object.keys(e[0]).length:e[0].length},_functionMap:function(e){for(var t=[],r=this._interpreter,n=e[0],i=e[1],s=0;s<i.length;s++)t.push(r.visit(n,i[s]));return t},_functionMerge:function(e){for(var t={},r=0;r<e.length;r++){var n=e[r];for(var i in n)t[i]=n[i]}return t},_functionMax:function(e){if(0<e[0].length){if(this._getTypeName(e[0][0])===c)return Math.max.apply(Math,e[0]);for(var t=e[0],r=t[0],n=1;n<t.length;n++)r.localeCompare(t[n])<0&&(r=t[n]);return r}return null},_functionMin:function(e){if(0<e[0].length){if(this._getTypeName(e[0][0])===c)return Math.min.apply(Math,e[0]);for(var t=e[0],r=t[0],n=1;n<t.length;n++)t[n].localeCompare(r)<0&&(r=t[n]);return r}return null},_functionSum:function(e){for(var t=0,r=e[0],n=0;n<r.length;n++)t+=r[n];return t},_functionType:function(e){switch(this._getTypeName(e[0])){case c:return"number";case h:return"string";case u:return"array";case t:return"object";case 5:return"boolean";case r:return"expref";case 7:return"null"}},_functionKeys:function(e){return Object.keys(e[0])},_functionValues:function(e){for(var t=e[0],r=Object.keys(t),n=[],i=0;i<r.length;i++)n.push(t[r[i]]);return n},_functionJoin:function(e){var t=e[0];return e[1].join(t)},_functionToArray:function(e){return this._getTypeName(e[0])===u?e[0]:[e[0]]},_functionToString:function(e){return this._getTypeName(e[0])===h?e[0]:JSON.stringify(e[0])},_functionToNumber:function(e){var t,r=this._getTypeName(e[0]);return r===c?e[0]:r!==h||(t=+e[0],isNaN(t))?null:t},_functionNotNull:function(e){for(var t=0;t<e.length;t++)if(7!==this._getTypeName(e[t]))return e[t];return null},_functionSort:function(e){var t=e[0].slice(0);return t.sort(),t},_functionSortBy:function(e){var t=e[0].slice(0);if(0===t.length)return t;var i=this._interpreter,s=e[1],a=this._getTypeName(i.visit(s,t[0]));if([c,h].indexOf(a)<0)throw new Error("TypeError");for(var u=this,r=[],n=0;n<t.length;n++)r.push([n,t[n]]);r.sort(function(e,t){var r=i.visit(s,e[1]),n=i.visit(s,t[1]);if(u._getTypeName(r)!==a)throw new Error("TypeError: expected "+a+", received "+u._getTypeName(r));if(u._getTypeName(n)!==a)throw new Error("TypeError: expected "+a+", received "+u._getTypeName(n));return n<r?1:r<n?-1:e[0]-t[0]});for(var o=0;o<r.length;o++)t[o]=r[o][1];return t},_functionMaxBy:function(e){for(var t,r,n=e[1],i=e[0],s=this.createKeyFunction(n,[c,h]),a=-1/0,u=0;u<i.length;u++)a<(r=s(i[u]))&&(a=r,t=i[u]);return t},_functionMinBy:function(e){for(var t,r,n=e[1],i=e[0],s=this.createKeyFunction(n,[c,h]),a=1/0,u=0;u<i.length;u++)(r=s(i[u]))<a&&(a=r,t=i[u]);return t},createKeyFunction:function(n,i){var s=this,a=this._interpreter;return function(e){var t=a.visit(n,e);if(i.indexOf(s._getTypeName(t))<0){var r="TypeError: expected one of "+i+", received "+s._getTypeName(t);throw new Error(r)}return t}}},e.tokenize=function(e){return(new n).tokenize(e)},e.compile=function(e){return(new Z).parse(e)},e.search=function(e,t){var r=new Z,n=new Y,i=new X(n);n._interpreter=i;var s=r.parse(t);return i.search(s,e)},e.strictDeepEqual=O}("undefined"==typeof exports?this.jmespath={}:exports);
</script>

Проверьте репозиторий github для реализации JMESPath javascript , которую вы можете использовать непосредственно в своих проектах скриптов приложений.

0 голосов
/ 23 мая 2019

Вы можете использовать forEach. map создаст новый массив. Таким образом, использование map приведет к вложенному массиву, подобному

[
  ["1-1 Benban Arinna Solar PV II"]
]

var arr = [{
  "id": 18,
  "published": 1,
  "include_inproject": 1,
  "created_at": "2017-09-21 11:27:46",
  "updated_at": "2018-06-18 15:35:38",
  "name": "1-1 Benban Arinna Solar PV II",
  "status_id": 15,
  "capacity": 20,
  "technology_id": 2,
  "commercial_operations": "2019-03-31 00:00:00",
  "commercial_operations_estemated": "Q1 2019",
  "commercial_operations_end": "",
  "commercial_operations_end_estemated": "",
  "start_construction": "2018-06-18 00:00:00",
  "project_id": 530,
  "start_construction_estimated": "June 2018",
  "capacity_low": "",
  "capacity_high": "",
  "technology": "Photovoltaic (PV)",
  "country": "Egypt",
  "region": "North Africa",
  "fuels": "Solar",
  "status": "Planned",
  "ownership_type": "IPP",
  "Units": [{
    "id": 1,
    "published": 1,
    "include_inproject": 1,
    "created_at": "2017-09-21 12:14:47",
    "updated_at": "2017-09-21 12:14:47",
    "name": "1-1 Benban Arinna Solar PV II",
    "grid_connection": "On-grid",
    "status_id": 14,
    "capacity": 20,
    "technology_id": 1,
    "commercial_operations": "1959-01-01 00:00:00",
    "commercial_operations_estemated": "1959",
    "commercial_operations_end": null,
    "commercial_operations_end_estemated": "",
    "start_construction": null,
    "project_id": 470,
    "start_construction_estimated": "",
    "capacity_low": null,
    "capacity_high": null
  }]
}]
let arys = []
arr.forEach(function(item) {

  return item.Units.forEach(function(elem) {
    arys.push(elem.name)
  })

});

console.log(arys)
0 голосов
/ 23 мая 2019

Вы можете сделать рекурсивную функцию, чтобы получить все имена до n-уровня.Следующая функция вернет массив всех имен на всех уровнях массива объектов.

Попробуйте выполнить следующее:

let arr = [ { "id": 18, "published": 1, "include_inproject": 1, "created_at": "2017-09-21 11:27:46", "updated_at": "2018-06-18 15:35:38", "name": "1-1 Benban Arinna Solar PV II", "status_id": 15, "capacity": 20, "technology_id": 2, "commercial_operations": "2019-03-31 00:00:00", "commercial_operations_estemated": "Q1 2019", "commercial_operations_end": "", "commercial_operations_end_estemated": "", "start_construction": "2018-06-18 00:00:00", "project_id": 530, "start_construction_estimated": "June 2018", "capacity_low": "", "capacity_high": "", "technology": "Photovoltaic (PV)", "country": "Egypt", "region": "North Africa", "fuels": "Solar", "status": "Planned", "ownership_type": "IPP", "Units": [ { "id": 1, "published": 1, "include_inproject": 1, "created_at": "2017-09-21 12:14:47", "updated_at": "2017-09-21 12:14:47", "name": "1-1 Benban Arinna Solar PV II", "grid_connection": "On-grid", "status_id": 14, "capacity": 20, "technology_id": 1, "commercial_operations": "1959-01-01 00:00:00", "commercial_operations_estemated": "1959", "commercial_operations_end": null, "commercial_operations_end_estemated": "", "start_construction": null, "project_id": 470, "start_construction_estimated": "", "capacity_low": null, "capacity_high": null } ] } ]

function getAllNames(arr){
  if(!arr)
    return [];
  let result = [];
  arr.forEach(({name, Units})=>{
    result.push(name);
    result = result.concat(getAllNames(Units));
  });
  return result;
}


console.log(getAllNames(arr));
0 голосов
/ 23 мая 2019

Этот код перебирает каждый объект. Единицы и помещает имя в массив:

var arr = [{
  "id": 18,
  "published": 1,
  "include_inproject": 1,
  "created_at": "2017-09-21 11:27:46",
  "updated_at": "2018-06-18 15:35:38",
  "name": "1-1 Benban Arinna Solar PV II",
  "status_id": 15,
  "capacity": 20,
  "technology_id": 2,
  "commercial_operations": "2019-03-31 00:00:00",
  "commercial_operations_estemated": "Q1 2019",
  "commercial_operations_end": "",
  "commercial_operations_end_estemated": "",
  "start_construction": "2018-06-18 00:00:00",
  "project_id": 530,
  "start_construction_estimated": "June 2018",
  "capacity_low": "",
  "capacity_high": "",
  "technology": "Photovoltaic (PV)",
  "country": "Egypt",
  "region": "North Africa",
  "fuels": "Solar",
  "status": "Planned",
  "ownership_type": "IPP",
  "Units": [{
    "id": 1,
    "published": 1,
    "include_inproject": 1,
    "created_at": "2017-09-21 12:14:47",
    "updated_at": "2017-09-21 12:14:47",
    "name": "1-1 Benban Arinna Solar PV II",
    "grid_connection": "On-grid",
    "status_id": 14,
    "capacity": 20,
    "technology_id": 1,
    "commercial_operations": "1959-01-01 00:00:00",
    "commercial_operations_estemated": "1959",
    "commercial_operations_end": null,
    "commercial_operations_end_estemated": "",
    "start_construction": null,
    "project_id": 470,
    "start_construction_estimated": "",
    "capacity_low": null,
    "capacity_high": null
  }]
}]



var names = []
arr.forEach(obj => obj.Units.forEach(value => names.push(value.name)))


console.log(names)
...